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

// GET /api/auth/discordID/:discordID/characterID/:characterID/refresh
export async function GET({ store, route: { params } }: RequestContext) {

  const discordID = params!['discordID'] as string;
  const characterID = params!['characterID'] as string;

  const user = UserHelper.findByDiscordId(discordID);
  const character = CharacterHelper.findByUserAndEveID(user.id, Number(characterID));
  if (!user) {
    throw new Error(`User not found for discordID: ${discordID}`);
  }
  if (!character) {
    throw new Error(`Character not found for user: ${user.id} and characterID: ${characterID}`);
  }
  const scopes = CharacterHelper.getScopes(character);

  const eveauth: EVEAuth = store.get('eveauth');
  const response = await eveauth.redirect(joinScopes(...scopes));
  setCookie(response, 'discordID', discordID, 60 * 10 /* 10 min */);
  setCookie(response, 'characterID', characterID, 60 * 10 /* 10 min */);
  return response;
}