import { ActionError, defineAction } from 'astro:actions';
import { z } from 'astro:schema';
import { db } from '@db/database.ts';
import { ADMIN_USER, ADMIN_PASSWORD } from 'astro:env/server';
import { Session } from '@util/session.ts';
import { Permissions } from '@util/permissions.ts';

export const session = {
  login: defineAction({
    input: z.object({
      username: z.string(),
      password: z.string()
    }),
    handler: async (input, context) => {
      let admin;
      if (input.username === ADMIN_USER && input.password === ADMIN_PASSWORD) {
        admin = {
          id: -1,
          username: ADMIN_USER,
          permissions: new Permissions(Permissions.allPermissions())
        };
      } else {
        admin = await db.existsAdmin(input);
      }

      if (!admin) {
        throw new ActionError({
          code: 'UNAUTHORIZED',
          message: 'Nutzername und Passwort stimmen nicht überein'
        });
      }

      Session.newSession(admin.id, admin.permissions, context.cookies);

      return {
        id: admin.id,
        username: admin.username,
        permissions: admin.permissions.value
      };
    }
  }),
  logout: defineAction({
    handler: async (_, context) => {
      const session = Session.actionSessionFromCookies(context.cookies);

      session.invalidate(context.cookies);
    }
  })
};
