import { createClient } from "https://esm.sh/@supabase/supabase-js@2";

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};

Deno.serve(async (req) => {
  // Handle CORS preflight
  if (req.method === "OPTIONS") {
    return new Response(null, { headers: corsHeaders });
  }

  try {
    const supabaseUrl = Deno.env.get("SUPABASE_URL")!;
    const supabaseServiceKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;
    const supabaseAnonKey = Deno.env.get("SUPABASE_ANON_KEY")!;

    // Create client with user's auth to verify admin status
    const authHeader = req.headers.get("Authorization");
    if (!authHeader) {
      return new Response(
        JSON.stringify({ error: "Unauthorized" }),
        { status: 401, headers: { ...corsHeaders, "Content-Type": "application/json" } }
      );
    }

    const userClient = createClient(supabaseUrl, supabaseAnonKey, {
      global: { headers: { Authorization: authHeader } },
    });

    // Verify the user is an admin
    const { data: { user }, error: authError } = await userClient.auth.getUser();
    if (authError || !user) {
      console.error("Auth error:", authError);
      return new Response(
        JSON.stringify({ error: "Unauthorized" }),
        { status: 401, headers: { ...corsHeaders, "Content-Type": "application/json" } }
      );
    }

    // Check admin role using service client
    const adminClient = createClient(supabaseUrl, supabaseServiceKey);
    
    const { data: roleData, error: roleError } = await adminClient
      .from("user_roles")
      .select("role")
      .eq("user_id", user.id)
      .eq("role", "admin")
      .maybeSingle();

    if (roleError || !roleData) {
      console.error("Role check failed:", roleError);
      return new Response(
        JSON.stringify({ error: "Admin access required" }),
        { status: 403, headers: { ...corsHeaders, "Content-Type": "application/json" } }
      );
    }

    console.log("Admin verified, resetting demo data...");

    // Demo account emails
    const demoEmails = ["admin@demo.com", "user@demo.com"];

    // Get demo user IDs from auth.users (need service role for this)
    const { data: authUsers } = await adminClient.auth.admin.listUsers();
    const demoUserIds = authUsers?.users
      ?.filter((u) => demoEmails.includes(u.email || ""))
      .map((u) => u.id) || [];

    console.log("Found demo user IDs:", demoUserIds);

    // Clean up demo user data (keeping the users themselves)
    for (const userId of demoUserIds) {
      // Delete projects and builds
      await adminClient.from("app_builds").delete().eq("user_id", userId);
      await adminClient.from("app_projects").delete().eq("user_id", userId);
      
      // Delete automation data
      await adminClient.from("automation_logs").delete().eq("user_id", userId);
      await adminClient.from("automation_configs").delete().eq("user_id", userId);
      
      // Delete chat messages
      await adminClient.from("chat_messages").delete().eq("user_id", userId);
      
      // Delete templates
      await adminClient.from("app_templates").delete().eq("user_id", userId);
      
      // Reset credits
      await adminClient
        .from("user_credits")
        .update({ monthly_credits: 50, bonus_credits: 10, credits_reset_at: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString() })
        .eq("user_id", userId);

      // Delete credit history
      await adminClient.from("credit_usage_history").delete().eq("user_id", userId);

      console.log(`Cleaned data for user: ${userId}`);
    }

    // Get demo user profiles
    const { data: demoProfiles } = await adminClient
      .from("profiles")
      .select("id, email")
      .in("email", demoEmails);

    // Ensure demo roles are set correctly
    for (const profile of demoProfiles || []) {
      // Delete existing roles
      await adminClient.from("user_roles").delete().eq("user_id", profile.id);

      // Set correct role
      const role = profile.email === "admin@demo.com" ? "admin" : "user";
      await adminClient.from("user_roles").insert({
        user_id: profile.id,
        role,
      });

      console.log(`Set role ${role} for ${profile.email}`);
    }

    // Create sample projects for demo admin
    const adminProfile = demoProfiles?.find((p) => p.email === "admin@demo.com");
    if (adminProfile) {
      const sampleProjects = [
        {
          user_id: adminProfile.id,
          app_name: "My E-Commerce App",
          website_url: "https://example-shop.com",
          description: "Convert your online store to a mobile app",
          primary_color: "#22D3EE",
          accent_color: "#A855F7",
          features: ["push-notifications", "offline-mode", "biometric-auth"],
          build_status: "completed",
        },
        {
          user_id: adminProfile.id,
          app_name: "Portfolio Website",
          website_url: "https://portfolio.example.com",
          description: "Personal portfolio converted to PWA",
          primary_color: "#10B981",
          accent_color: "#F59E0B",
          features: ["offline-mode"],
          build_status: "draft",
        },
        {
          user_id: adminProfile.id,
          app_name: "Restaurant Menu",
          website_url: "https://restaurant.example.com",
          description: "Digital menu app for restaurants",
          primary_color: "#EF4444",
          accent_color: "#FBBF24",
          features: ["push-notifications", "qr-scanner"],
          build_status: "building",
        },
      ];

      await adminClient.from("app_projects").insert(sampleProjects);
      console.log("Created sample projects for demo admin");
    }

    // Create sample project for demo user
    const userProfile = demoProfiles?.find((p) => p.email === "user@demo.com");
    if (userProfile) {
      await adminClient.from("app_projects").insert({
        user_id: userProfile.id,
        app_name: "My First App",
        website_url: "https://myblog.example.com",
        description: "Blog converted to mobile app",
        primary_color: "#3B82F6",
        accent_color: "#EC4899",
        features: ["offline-mode"],
        build_status: "draft",
      });
      console.log("Created sample project for demo user");
    }

    return new Response(
      JSON.stringify({
        success: true,
        message: "Demo data reset successfully",
        resetUsers: demoEmails,
      }),
      { status: 200, headers: { ...corsHeaders, "Content-Type": "application/json" } }
    );
  } catch (error: unknown) {
    console.error("Error resetting demo data:", error);
    const message = error instanceof Error ? error.message : "Unknown error";
    return new Response(
      JSON.stringify({ error: "Failed to reset demo data", details: message }),
      { status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } }
    );
  }
});
