import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import { createClient as createSupabaseClient } from "@supabase/supabase-js";
import { digitsOnly, validateBrazilianDocument } from "@/lib/document-utils";
import { createAdminClient } from "@/lib/supabase-admin";

export async function POST(request: Request) {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get("ks_client_portal")?.value || "";
    if (!token) {
      return NextResponse.json({ error: "Sessão inválida." }, { status: 401 });
    }

    const body = (await request.json()) as {
      slug?: string;
      name?: string;
      company_name?: string;
      document?: string;
      email?: string;
      phone?: string;
      whatsapp?: string;
      address_zip?: string;
      address_street?: string;
      address_number?: string;
      address_complement?: string;
      address_neighborhood?: string;
      address_city?: string;
      address_state?: string;
      notes?: string;
    };

    const slug = String(body?.slug || "").trim();
    const document = digitsOnly(body?.document || "").slice(0, 14);
    if (!slug) {
      return NextResponse.json({ error: "Loja inválida." }, { status: 400 });
    }
    if (document && !validateBrazilianDocument(document)) {
      return NextResponse.json({ error: "Informe um CPF ou CNPJ válido." }, { status: 400 });
    }

    const admin = createAdminClient();

    // Verify session to get the current client ID and check if they already have a document
    const sessionResult = await admin.rpc("client_portal_get_session", {
      p_slug: slug,
      p_session_token: token,
    });
    const sessionPayload = sessionResult.data;
    if (sessionResult.error || !sessionPayload?.client?.id) {
      return NextResponse.json({ error: "Sessão inválida." }, { status: 401 });
    }

    const currentDocument = digitsOnly(sessionPayload.client.document || "").slice(0, 14);
    if (currentDocument && document !== currentDocument) {
      return NextResponse.json(
        { error: "O CPF/CNPJ deste cadastro já está definido e não pode ser alterado por aqui." },
        { status: 400 }
      );
    }

    // Get the profile ID to check for conflicting documents in the same store
    const { data: profile } = await admin
      .from("profiles")
      .select("id")
      .eq("slug", slug)
      .maybeSingle();

    if (!profile?.id) {
      return NextResponse.json({ error: "Loja não encontrada." }, { status: 404 });
    }

    if (document) {
      const { data: conflictingClient, error: conflictingClientError } = await admin
        .from("clients")
        .select("id")
        .eq("user_id", profile.id)
        .eq("document", document)
        .neq("id", sessionPayload.client.id)
        .eq("active", true)
        .or("is_deleted.is.null,is_deleted.eq.false")
        .maybeSingle();

      if (conflictingClientError) {
        return NextResponse.json({ error: "Não foi possível validar o CPF/CNPJ informado." }, { status: 500 });
      }

      if (conflictingClient?.id) {
        return NextResponse.json(
          { error: "Este CPF/CNPJ já está vinculado a outro cliente cadastrado nesta loja." },
          { status: 400 }
        );
      }
    }

    const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
    const anon = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
    if (!url || !anon) {
      return NextResponse.json({ error: "Configuração do Supabase ausente." }, { status: 500 });
    }

    const supabase = createSupabaseClient(url, anon);
    const { data, error } = await supabase.rpc("client_portal_update_profile", {
      p_slug: slug,
      p_session_token: token,
      p_name: body?.name || null,
      p_company_name: body?.company_name || null,
      p_document: document || null,
      p_email: body?.email || null,
      p_phone: body?.phone || null,
      p_whatsapp: body?.whatsapp || null,
      p_address_zip: body?.address_zip || null,
      p_address_street: body?.address_street || null,
      p_address_number: body?.address_number || null,
      p_address_complement: body?.address_complement || null,
      p_address_neighborhood: body?.address_neighborhood || null,
      p_address_city: body?.address_city || null,
      p_address_state: body?.address_state || null,
      p_notes: body?.notes || null,
    });

    if (error || !data?.ok) {
      return NextResponse.json({ error: error?.message || "Não foi possível salvar seu cadastro." }, { status: 400 });
    }

    /* Marca que a alteracao veio do cliente, e nao da loja. Sem isso o cadastro
       mudava no admin sem ninguem saber que foi o proprio cliente que mexeu —
       e nao havia como diferenciar de uma edicao interna. */
    const clientId = String(sessionPayload.client.id || "").trim();
    if (clientId) {
      await admin
        .from("clients")
        .update({ profile_updated_by_client_at: new Date().toISOString() })
        .eq("id", clientId);
    }

    return NextResponse.json({ ok: true });
  } catch (err) {
    const message =
      typeof err === "object" && err && "message" in err && typeof err.message === "string"
        ? err.message
        : "Não foi possível salvar seu cadastro.";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}