import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { verifyPasswordOrDummy, createSession } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { readJsonBody } from '@/lib/http';
import { rateLimit, clientIpFromHeaders } from '@/lib/rateLimit';

const loginSchema = z.object({
  email: z.string().email(),
  password: z.string().min(1),
});

export async function POST(request: NextRequest) {
  try {
    // Per-IP cap, sharing the `login:${ip}` bucket with the UI login
    // server action (app/auth/login/actions.ts): 10 attempts / 15 min.
    // Without this the raw API endpoint is an uncapped credential-stuffing
    // surface that bypasses the server-action's limiter.
    const ip = clientIpFromHeaders(request.headers);
    const limited = rateLimit(`login:${ip}`, { limit: 10, windowMs: 15 * 60_000 });
    if (!limited.ok) {
      return NextResponse.json(
        { error: `Too many login attempts. Try again in ${limited.retryAfterSec}s.` },
        { status: 429, headers: { 'Retry-After': String(limited.retryAfterSec) } }
      );
    }

    const body = await readJsonBody(request);
    const { email, password } = loginSchema.parse(body);

    // Look up user by email
    const user = await prisma.user.findUnique({
      where: { email },
    });

    // Always run a bcrypt compare (against a dummy hash when the email is
    // unknown) so response time doesn't reveal whether an account exists.
    const isValid = await verifyPasswordOrDummy(
      password,
      user?.passwordHash ?? null,
    );

    if (!user || !isValid) {
      return NextResponse.json(
        { error: 'Invalid email or password' },
        { status: 401 }
      );
    }

    // Create a session
    const session = await createSession(user.id);

    // Set the session cookie
    const response = NextResponse.json({
      success: true,
      user: {
        id: user.id,
        email: user.email,
        name: user.name,
      },
    });

    response.cookies.set('sessionToken', session.token, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 60 * 60 * 24 * 30, // 30 days
      path: '/',
    });

    return response;
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { error: 'Invalid request data', details: error.errors },
        { status: 400 }
      );
    }

    console.error('Login error:', error);
    return NextResponse.json(
      { error: 'An error occurred during login' },
      { status: 500 }
    );
  }
}
