import type { Handler } from 'hono';
import { getUserByEmail, getPasskeysByUserIdAndOrigin } from 'officerdb';
import { sign } from '@@/jwt';
import argon2 from 'argon2';
import * as errors from '@@/custom-errors';
import { isSuperAdminOnlyOrigin } from '@@/_middlewares';
import { isSuperAdmin } from '@@/super-admin';
import { isLockdown, noteBlocked } from './panic';

const TEST_USERS: number[] = [];

export const signinHandler: Handler = async function (ctx) {
  const { email, password } = ctx.get('body');
  const origin = ctx.get('origin');

  // Panic lockdown active → refuse all logins (looks like a normal failed login).
  if (isLockdown()) {
    noteBlocked('login attempt');
    throw errors.UNAUTHORIZED();
  }

  const dbUser = await getUserByEmail(email);
  if (!dbUser) throw errors.UNAUTHORIZED();

  const passkeys = await getPasskeysByUserIdAndOrigin(dbUser.id, origin);

  if (!dbUser.password) throw errors.UNAUTHORIZED();
  const { status } = dbUser;
  if (status !== 'Active') throw errors.UNAUTHORIZED();
  const isValidPassword = TEST_USERS.includes(dbUser.id) || (await argon2.verify(dbUser.password, password));
  if (!isValidPassword) throw errors.UNAUTHORIZED();

  // A non-owner account may authenticate only through an app origin (e.g. the music app), never the
  // Super-Admin-only web/mobile origins — so its credentials can't open the full platform in a browser.
  if (isSuperAdminOnlyOrigin(origin) && !(await isSuperAdmin({ id: dbUser.id }))) {
    throw errors.FORBIDDEN('This account can only sign in through its app.');
  }

  const { id, name, username } = dbUser;

  const tokenUser = { id, email, name, username, passkeys: passkeys.length };

  if (passkeys.length > 0 && !origin.startsWith('chrome-extension://') && !TEST_USERS.includes(dbUser.id)) {
    return ctx.json({ user: tokenUser });
  }

  const token = await sign(tokenUser);

  if (origin.startsWith('chrome-extension://')) {
    // console.log('token', token);
  }

  return ctx.json({ token, user: tokenUser });
};
