import type { FastifyRequest, FastifyReply } from 'fastify';
import { login, getSessionUser } from '../services/auth.service.js';
import { findById as findEmployeeById } from '../repositories/employee.repo.js';
import { emitter } from '../events/emitter.js';
import { logger } from '../utils/logger.js';
import type { LoginPayload } from '../types/index.js';

export async function loginHandler(request: FastifyRequest, reply: FastifyReply) {
  const { identifier, password, rememberMe } = request.body as LoginPayload;

  let result;
  try {
    result = await login(identifier, password, rememberMe);
  } catch (err) {
    const message = err instanceof Error ? err.message : 'Login failed';
    logger.warn({ identifier, ip: request.ip }, `Failed login attempt: ${message}`);
    emitter.emit('activity.create', {
      entity_type: 'auth',
      action: 'login_failed',
      description: `Failed login attempt for "${identifier}": ${message}`,
      ip_address: request.ip,
    });
    throw err;
  }

  const { user, token } = result;

  reply.setCookie('session', token, {
    httpOnly: true,
    sameSite: 'strict',
    path: '/api',
    // Based on the actual connection, not NODE_ENV — a "Secure" cookie is
    // silently dropped by the browser over plain http, which broke session
    // login when testing production-DB mode over local http://localhost.
    secure: request.protocol === 'https',
    maxAge: rememberMe ? 30 * 24 * 60 * 60 : 24 * 60 * 60,
  });

  return { user };
}

export async function sessionHandler(request: FastifyRequest, reply: FastifyReply) {
  const userId = request.user?.id;
  if (!userId) {
    return reply.status(401).send({ error: 'Authentication required' });
  }

  const employee = await findEmployeeById(userId);
  if (!employee) {
    return reply.status(401).send({ error: 'User not found' });
  }

  const user = await getSessionUser(userId, employee.email);
  if (!user) {
    return reply.status(401).send({ error: 'Account no longer has access' });
  }

  return { user };
}

export async function logoutHandler(_request: FastifyRequest, reply: FastifyReply) {
  reply.clearCookie('session', { path: '/api' });
  return { ok: true };
}
