import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { verifyNativePassword } from '@/core/auth/password-native';
import { signJwt, setSessionCookie } from '@/core/auth';
import { isNativeAuthEnabled } from '@/core/auth/standalone';

/** Defer SQLite until request time — parallel `next build` workers otherwise lock the DB. */
export const dynamic = 'force-dynamic';

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

const DEFAULT_TTL_SEC = 86_400;

async function delay(ms: number): Promise<void> {
  await new Promise((r) => setTimeout(r, ms));
}

export async function POST(req: NextRequest): Promise<NextResponse> {
  if (!isNativeAuthEnabled()) {
    return NextResponse.json({ error: 'Not found' }, { status: 404 });
  }

  let json: unknown;
  try {
    json = await req.json();
  } catch {
    return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
  }

  const parsed = bodySchema.safeParse(json);
  if (!parsed.success) {
    return NextResponse.json({ error: 'Invalid credentials' }, { status: 400 });
  }

  const { email, password } = parsed.data;
  const { getUserByEmail, touchUserLastLogin } = await import('@/lib/db/users-repo');
  const user = getUserByEmail(email);
  if (!user?.passwordHash) {
    await delay(350);
    return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 });
  }

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

  const { getAllWorkspaces } = await import('@/lib/db/repositories');
  const workspaces = getAllWorkspaces();
  const ttl = Math.min(
    Math.max(300, Number(process.env.MAILFORGE_NATIVE_SESSION_TTL_SEC) || DEFAULT_TTL_SEC),
    86400 * 7,
  );

  const permissions = user.role === 'admin' ? ['*'] : ['editor'];
  const token = await signJwt(
    {
      userId: user.id,
      workspaceIds: workspaces.map((w) => w.id),
      permissions,
      email: user.email,
      displayName: user.name ?? user.email,
    },
    ttl,
  );

  touchUserLastLogin(user.id);

  const res = NextResponse.json({ ok: true });
  setSessionCookie({ response: res, token, maxAge: ttl });
  return res;
}
