/**
 * Netlify Function: Login
 * Faz proxy seguro para API Supabase com apikey protegida
 */

import type { Handler, HandlerEvent } from "@netlify/functions";

// Constantes da API (protegidas no backend)
const SUPABASE_URL = "https://yuanqfswhberkoevtmfr.supabase.co";
const SUPABASE_ANON_KEY =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ";

interface LoginRequest {
  email: string;
  password: string;
}

export const handler: Handler = async (event: HandlerEvent) => {
  // CORS headers
  const headers = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers": "Content-Type, Authorization",
    "Access-Control-Allow-Methods": "POST, OPTIONS",
  };

  // Handle preflight
  if (event.httpMethod === "OPTIONS") {
    return {
      statusCode: 200,
      headers,
      body: "",
    };
  }

  // Apenas POST é permitido
  if (event.httpMethod !== "POST") {
    return {
      statusCode: 405,
      headers,
      body: JSON.stringify({ error: "Method Not Allowed" }),
    };
  }

  try {
    // Parse body
    const body: LoginRequest = JSON.parse(event.body || "{}");

    if (!body.email || !body.password) {
      // Log headers and raw body to help debugging malformed requests from frontend
      console.error(
        "[auth-login] Requisição inválida - falta email ou password. Headers:",
        event.headers
      );
      console.error("[auth-login] Raw body:", event.body);
      return {
        statusCode: 400,
        headers,
        body: JSON.stringify({ error: "Email e senha são obrigatórios" }),
      };
    }

    // Faz requisição para API Supabase COM a apikey protegida
    const response = await fetch(
      `${SUPABASE_URL}/auth/v1/token?grant_type=password`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          apikey: SUPABASE_ANON_KEY,
        },
        body: JSON.stringify({
          email: body.email,
          password: body.password,
        }),
      }
    );

    const data = await response.json();

    // Repassa a resposta para o frontend
    return {
      statusCode: response.status,
      headers: {
        ...headers,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    };
  } catch (error) {
    console.error("Erro no login:", error);

    return {
      statusCode: 500,
      headers,
      body: JSON.stringify({
        error: "Erro interno no servidor",
        message: error instanceof Error ? error.message : "Erro desconhecido",
      }),
    };
  }
};
