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

/**
 * GET /offline/agenda-today
 * Retornar agenda simplificada do dia para modo offline
 * 
 * Returns:
 * {
 *   date: date,
 *   appointments: [{
 *     id: uuid,
 *     doctor_id: uuid,
 *     time: time,
 *     status: string,
 *     notes: 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);
    }

    const today = new Date().toISOString().split("T")[0];

    // Buscar agendamentos do dia no Supabase externo
    const appRes = await externalRest(
      `/rest/v1/appointments?patient_id=eq.${auth.userId}&date=eq.${today}`,
      "GET"
    );

    if (appRes.status >= 400) {
      return errorResponse("Falha ao buscar agendamentos");
    }

    return jsonResponse({
      date: today,
      appointments: appRes.data || [],
      last_sync: new Date().toISOString(),
    });
  } catch (error: unknown) {
    const err = error as Error;
    return errorResponse(err.message, 500);
  }
});
