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"])) {
      return errorResponse("Não autorizado", 401);
    }

    if (req.method === "GET") {
      const res = await mydb.from("feature_flags").select("*");
      return jsonResponse({ flags: res.data || [] });
    }

    if (req.method === "POST") {
      const body = await req.json();
      const { name, enabled, rollout_percentage } = body;

      const res = await mydb
        .from("feature_flags")
        .update({ enabled, rollout_percentage })
        .eq("name", name)
        .select();

      return jsonResponse({ success: true, flag: res.data?.[0] });
    }

    return errorResponse("Method not allowed", 405);
  } catch (error: unknown) {
    const err = error as Error;
    return errorResponse(err.message, 500);
  }
});
