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

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

  try {
    const auth = await validateAuth(req);
    if (!auth || !hasPermission(auth.role, ["admin", "secretary"])) {
      return errorResponse("Não autorizado", 401);
    }

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

    const url = new URL(req.url);
    const format = url.searchParams.get("format") || "pdf";

    const res = await mydb
      .from("export_jobs")
      .select("*")
      .eq("user_id", auth.userId)
      .order("created_at", { ascending: false });

    return jsonResponse({ exports: res.data || [] });
  } catch (error: unknown) {
    const err = error as Error;
    return errorResponse(err.message, 500);
  }
});
