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";

/**
 * POST /user-sync
 * Sincroniza usuário do Supabase externo para nossa plataforma
 *
 * Body:
 * {
 *   external_user_id: uuid,
 *   external_email: string,
 *   external_name: string,
 *   external_role: string
 * }
 */

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

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

    const body = await req.json();
    const { external_user_id, external_email, external_name, external_role } =
      body;

    if (!external_user_id || !external_email) {
      return errorResponse(
        "external_user_id e external_email são obrigatórios",
        400
      );
    }

    // 1. Verificar se já existe
    const existing = await mydb
      .from("user_sync")
      .select("*")
      .eq("external_user_id", external_user_id)
      .single();

    if (existing.data) {
      return jsonResponse({
        success: true,
        synced: true,
        message: "Usuário já sincronizado",
      });
    }

    // 2. Detectar tipo de perfil
    let profileType = "unknown";
    const roleStr = (external_role || "").toLowerCase();
    if (roleStr.includes("doctor") || roleStr.includes("medico")) {
      profileType = "doctor";
    } else if (
      roleStr.includes("secretary") ||
      roleStr.includes("secretaria")
    ) {
      profileType = "secretary";
    } else if (roleStr.includes("patient") || roleStr.includes("paciente")) {
      profileType = "patient";
    }

    // 3. Criar entrada de sincronização
    const syncRes = await mydb
      .from("user_sync")
      .insert({
        external_user_id,
        external_email,
        external_name,
        external_role,
        profile_type: profileType,
        sync_status: "synced",
        last_synced_at: new Date().toISOString(),
      })
      .select()
      .single();

    if (syncRes.error) {
      return errorResponse("Erro ao sincronizar usuário", 500);
    }

    // 4. Criar entrada em profile_sync
    await mydb.from("profile_sync").insert({
      external_user_id,
      full_name: external_name,
      email: external_email,
      role: profileType,
    });

    // 5. Registrar ação de sincronização
    await mydb.from("user_actions").insert({
      external_user_id,
      action_category: "system",
      action_type: "user_synced",
      action_description: `Usuário sincronizado como ${profileType}`,
      resource_type: "user_sync",
      status: "success",
    });

    return jsonResponse({
      success: true,
      synced: true,
      profile_type: profileType,
      message: "Usuário sincronizado com sucesso",
      sync_id: syncRes.data.id,
    });
  } catch (error: unknown) {
    console.error("[user-sync] Erro:", error);
    const err = error as Error;
    return errorResponse(err.message, 500);
  }
});
