import { fail, type Actions } from '@sveltejs/kit';

import {
  createKey,
  listKeys,
  revokeKey,
  countActiveKeys
} from '$lib/server/keys';
import { PLANS } from '$lib/plans';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ locals }) => {
  const account = locals.account!;
  const keys = listKeys(account.id);
  return {
    keys,
    activeCount: countActiveKeys(account.id),
    plan: PLANS[account.plan]
  };
};

export const actions: Actions = {
  create: async ({ request, locals }) => {
    const account = locals.account!;
    const form = await request.formData();
    const name = ((form.get('name') ?? '') as string).trim();
    const scopes = form.getAll('scopes').map((s) => s.toString());

    if (!name) {
      return fail(400, { error: 'Give the key a name so you can recognize it later.' });
    }

    const plan = PLANS[account.plan];
    const active = countActiveKeys(account.id);
    if (Number.isFinite(plan.maxKeys) && active >= plan.maxKeys) {
      return fail(403, {
        error: `Your ${plan.name} plan allows ${plan.maxKeys} active key${
          plan.maxKeys === 1 ? '' : 's'
        }. Revoke one or upgrade your plan first.`
      });
    }

    const created = createKey({
      accountId: account.id,
      name,
      scopes
    });

    return {
      created: {
        id: created.id,
        plaintext: created.plaintext,
        name: created.name
      }
    };
  },

  revoke: async ({ request, locals }) => {
    const account = locals.account!;
    const form = await request.formData();
    const id = (form.get('id') ?? '').toString();
    if (!id) return fail(400, { error: 'Missing key id.' });

    const ok = revokeKey(account.id, id);
    if (!ok) return fail(404, { error: 'Key not found.' });
    return { revokedId: id };
  }
};
