import type { APIRoute } from 'astro';
import { query } from '../../../../lib/db';
import { signToken, comparePassword } from '../../../../lib/auth';

export const POST: APIRoute = async ({ request }) => {
  try {
    const { email, password } = await request.json();

    if (!email || !password) {
      return new Response(JSON.stringify({ error: 'Email and password required' }), { status: 400 });
    }

    // Env-based admin fallback (no hardcoded credentials)
    const envEmail = process.env.ADMIN_EMAIL || '';
    const envPassword = process.env.ADMIN_PASSWORD || '';
    if (envEmail && envPassword && email === envEmail && password === envPassword) {
      const token = signToken({ email: envEmail, role: 'admin' });
      return new Response(JSON.stringify({ token, user: { email: envEmail, name: 'Admin' } }), {
        headers: {
          'Content-Type': 'application/json',
          'Set-Cookie': `admin_token=${token}; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=${7 * 86400}`,
        },
      });
    }

    // DB lookup
    const result = await query('SELECT * FROM admin_users WHERE email = $1 LIMIT 1', [email]);
    if (!result.rows.length) {
      return new Response(JSON.stringify({ error: 'Invalid credentials' }), { status: 401 });
    }

    const user = result.rows[0];
    const valid = await comparePassword(password, user.password_hash);
    if (!valid) {
      return new Response(JSON.stringify({ error: 'Invalid credentials' }), { status: 401 });
    }

    const token = signToken({ email: user.email, role: 'admin' });
    return new Response(JSON.stringify({ token, user: { email: user.email, name: user.name } }), {
      headers: {
        'Content-Type': 'application/json',
        'Set-Cookie': `admin_token=${token}; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=${7 * 86400}`,
      },
    });
  } catch (err) {
    console.error('Login error:', err);
    return new Response(JSON.stringify({ error: 'Internal error' }), { status: 500 });
  }
};
