import { NextResponse } from "next/server";
import { canCompany, getCompanyContext } from "@/lib/company-context";
import { createAdminClient, createClient } from "@/lib/supabase-server";

/*
  O que a tela do cliente precisa saber antes de mostrar qualquer coisa: a
  marca da loja e o endereço do canal por onde o balcão fala com ela. O PDV
  pergunta a mesma coisa, para os dois caírem no mesmo canal.
*/

export const runtime = "nodejs";

function texto(valor: unknown) {
  return String(valor ?? "").trim();
}

export async function GET() {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();
  if (!user) return NextResponse.json({ error: "Não autenticado." }, { status: 401 });

  const ctx = await getCompanyContext(supabase, user);
  if (!canCompany(ctx, user.id, "pdv.read")) {
    return NextResponse.json({ error: "Sem permissão para usar o PDV." }, { status: 403 });
  }

  const tenantId = ctx.ownerId || user.id;
  const admin = createAdminClient();
  const { data } = await admin
    .from("profiles")
    .select("catalog_name,store_name,catalog_logo_url,logo_url,primary_color,company_whatsapp,whatsapp,company_phone,phone,address,slug")
    .eq("id", tenantId)
    .maybeSingle();

  const perfil = (data || {}) as Record<string, unknown>;
  const cor = texto(perfil.primary_color);

  return NextResponse.json({
    ok: true,
    tenantId,
    loja: {
      nome: texto(perfil.catalog_name) || texto(perfil.store_name) || "Minha empresa",
      logo: texto(perfil.catalog_logo_url) || texto(perfil.logo_url) || null,
      cor: /^#[0-9a-f]{6}$/i.test(cor) ? cor : "#4425A7",
      whatsapp: texto(perfil.company_whatsapp) || texto(perfil.whatsapp) || null,
      telefone: texto(perfil.company_phone) || texto(perfil.phone) || null,
      endereco: texto(perfil.address) || null,
      slug: texto(perfil.slug) || null,
    },
  });
}
