import type { EVEAuth } from '@/middleware';
import { setCookie } from '@/utils';
import type { RequestContext } from 'brisa';
import { joinScopes, SCOPES } from '@star-kitten/eve/esi';

const allScopes = Object.values(SCOPES).filter((value) => typeof value === 'string') as string[];
const allScopesString = allScopes.join(' ');

const module_Scopes: { [key: string]: string } = {
  'Full ESI': allScopesString,
  'Public': joinScopes(SCOPES.PUBLIC_DATA),
  'Characters': joinScopes(SCOPES.PUBLIC_DATA),
  'Mail': joinScopes(SCOPES.MAIL_READ_MAIL, SCOPES.MAIL_SEND_MAIL, SCOPES.MAIL_ORGANIZE_MAIL),
  'Skills': joinScopes(SCOPES.SKILLS_READ_SKILLQUEUE, SCOPES.SKILLS_READ_SKILLS),
}

// GET /api/auth/discordID/:discordID/characterID/:characterID/modules/:modules
export async function GET({ store, route: { params } }: RequestContext) {
  // we need to check the modules that were sent, in order to get the correct scopes
  // that each module requires.
  let modules = (params!['modules'] as string).split(' ');
  let scopes = joinScopes(...modules.map((module) => module_Scopes[module]));

  const eveauth: EVEAuth = store.get('eveauth');
  const response = await eveauth.redirect(scopes);
  setCookie(response, 'discordID', params!['discordID'] as string, 60 * 10 /* 10 min */);
  setCookie(response, 'characterID', params!['characterID'] as string, 60 * 10 /* 10 min */);
  return response;
}