import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { externalRest } from "../../lib/externalSupabase.ts";
import { corsHeaders, jsonResponse, errorResponse } from "../../lib/utils.ts";
import { validateAuth } from "../../lib/auth.ts";

/**
 * GET /offline/patient-basic
 * Retornar dados básicos do paciente para modo offline
 * 
 * Returns:
 * {
 *   patient_id: uuid,
 *   name: string,
 *   email: string,
 *   phone: string,
 *   cpf: string,
 *   avatar_url?: string,
 *   last_sync: timestamptz
 * }
 */

serve(async (req) => {
  if (req.method === "OPTIONS") {
    return new Response("ok", { headers: corsHeaders() });
  }

  try {
    const auth = await validateAuth(req);
    if (!auth) {
      return errorResponse("Não autorizado", 401);
    }

    if (req.method !== "GET") {
      return errorResponse("Method not allowed", 405);
    }

    // Buscar dados do paciente no Supabase externo
    const patientRes = await externalRest(
      `/rest/v1/patients?id=eq.${auth.userId}`,
      "GET"
    );

    if (patientRes.status >= 400 || !patientRes.data?.[0]) {
      return errorResponse("Paciente não encontrado", 404);
    }

    const patient = patientRes.data[0];

    return jsonResponse({
      patient_id: patient.id,
      name: patient.name,
      email: patient.email,
      phone: patient.phone,
      cpf: patient.cpf,
      avatar_url: patient.avatar_url,
      last_sync: new Date().toISOString(),
    });
  } catch (error: unknown) {
    const err = error as Error;
    return errorResponse(err.message, 500);
  }
});
