import { ActionError, defineAction } from 'astro:actions';
import { Session } from '@util/session.ts';
import { Permissions } from '@util/permissions.ts';
import { z } from 'astro:schema';
import { getBedrockUuid, getJavaUuid } from '@util/minecraft.ts';

export const tools = {
  uuidFromUsername: defineAction({
    input: z.object({
      edition: z.enum(['java', 'bedrock']),
      username: z.string()
    }),
    handler: async (input, context) => {
      Session.actionSessionFromCookies(context.cookies, Permissions.Tools);

      let uuid = null;
      switch (input.edition) {
        case 'java':
          try {
            uuid = await getJavaUuid(input.username);
          } catch (_) {
            throw new ActionError({
              code: 'NOT_FOUND',
              message: `Der Username ${input.username} existiert nicht`
            });
          }
          if (uuid == null) {
            throw new ActionError({
              code: 'BAD_REQUEST',
              message: `Während der Anfrage zur Mojang API ist ein Fehler aufgetreten`
            });
          }
          break;
        case 'bedrock':
          try {
            uuid = await getBedrockUuid(input.username);
          } catch (_) {
            throw new ActionError({
              code: 'NOT_FOUND',
              message: `Der Username ${input.username} existiert nicht`
            });
          }
          if (uuid == null) {
            throw new ActionError({
              code: 'BAD_REQUEST',
              message: `Während der Anfrage zum Username Resolver ist ein Fehler aufgetreten`
            });
          }
          break;
      }

      return {
        uuid: uuid
      };
    }
  })
};
