import { defineAction } from 'astro:actions';
import { db } from '@db/database.ts';
import { z } from 'astro:schema';
import { Session } from '@util/session.ts';
import { Permissions } from '@util/permissions.ts';

export const admin = {
  addAdmin: defineAction({
    input: z.object({
      username: z.string(),
      password: z.string(),
      permissions: z.number()
    }),
    handler: async (input, context) => {
      Session.actionSessionFromCookies(context.cookies, Permissions.Admin);
      const { id } = await db.addAdmin(input);

      return {
        id: id
      };
    }
  }),
  editAdmin: defineAction({
    input: z.object({
      id: z.number(),
      username: z.string(),
      password: z.string().nullable(),
      permissions: z.number()
    }),
    handler: async (input, context) => {
      Session.actionSessionFromCookies(context.cookies, Permissions.Admin);

      await db.editAdmin(input);
    }
  }),
  deleteAdmin: defineAction({
    input: z.object({
      id: z.number()
    }),
    handler: async (input, context) => {
      Session.actionSessionFromCookies(context.cookies, Permissions.Admin);

      await db.deleteAdmin(input);
    }
  }),
  admins: defineAction({
    handler: async (_, context) => {
      Session.actionSessionFromCookies(context.cookies, Permissions.Admin);

      return {
        admins: await db.getAdmins({})
      };
    }
  })
};
