import { NextResponse } from 'next/server';
import { UserStatus } from '@prisma/client';
import { prisma } from '../../../../lib/prisma';
import { verifyPassword } from '../../../../lib/auth';
import { signAccessToken, buildSessionCookie, clearSessionCookie } from '../../../../lib/jwt';

export async function POST(req: Request) {
  try {
    const body = await req.json();
    const email = String(body.email ?? '').trim().toLowerCase();
    const password = String(body.password ?? '');

    if (!email || !password) {
      return NextResponse.json({ error: 'Email and password are required' }, { status: 400 });
    }

    const user = await prisma.user.findUnique({ where: { email } });
    if (!user) {
      return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 });
    }

    const valid = await verifyPassword(password, user.passwordHash);
    if (!valid) {
      return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 });
    }

    if (!user.emailVerifiedAt) {
      return NextResponse.json({ error: 'Email not verified yet' }, { status: 403 });
    }
    if (!user.approvedAt || user.status !== UserStatus.ACTIVE) {
      const statusMessage =
        user.status === UserStatus.REJECTED
          ? 'User access was rejected'
          : user.status === UserStatus.REMOVED
            ? 'User has been removed'
            : 'User is not approved yet';
      return NextResponse.json({ error: statusMessage }, { status: 403 });
    }

    const token = await signAccessToken({ userId: user.id, role: user.role });
    const res = NextResponse.json({ token, user: { id: user.id, role: user.role, email: user.email } });
    res.headers.append('Set-Cookie', buildSessionCookie(token));
    return res;
  } catch (error) {
    console.error('Login error', error);
    const res = NextResponse.json({ error: 'Login failed' }, { status: 500 });
    res.headers.append('Set-Cookie', clearSessionCookie());
    return res;
  }
}
