import { NextResponse } from "next/server";
import { createAdminClient, createClient } from "@/lib/supabase-server";
import { validarAjustesDePermissao } from "@/lib/ajustes-de-permissao";
import { assistentesLiberadosAgora } from "@/lib/assistentes/ajustes";
import { digitaisLiberadosAgora } from "@/lib/digitais/liberacao-do-banco";
import { designLiberado } from "@/lib/banner-editor/liberacao";
import { revogarAcessosDosAssistentes } from "@/lib/assistentes/painel";
import { canCompanyRole } from "@/lib/company-context";

type CompanyRole =
  | "owner"
  | "admin"
  | "manager"
  | "financial"
  | "production"
  | "sales"
  | "viewer";

type MutableCompanyRole = Exclude<CompanyRole, "owner">;

type CompanyUserRow = {
  id: string;
  company_id: string;
  user_id: string;
  email: string;
  role: CompanyRole;
  permissions: unknown;
  active: boolean;
  created_at: string;
  updated_at: string;
};

type SalesOptionRow = {
  user_id: string;
  email: string;
  role: CompanyRole;
  active: boolean;
};

function isValidEmail(value: string) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
}

function normalizeMutableRole(value: unknown): MutableCompanyRole | null {
  if (
    value === "admin" ||
    value === "manager" ||
    value === "financial" ||
    value === "production" ||
    value === "sales" ||
    value === "viewer"
  ) {
    return value;
  }
  return null;
}

function getResetBaseUrl(req: Request) {
  // Forçar URL de produção para garantir HTTPS e domínio correto
  if (process.env.NODE_ENV === "production") {
    return "https://admin.ktalogu.com.br";
  }

  const envBase = process.env.NEXT_PUBLIC_ADMIN_BASE_URL || process.env.ADMIN_BASE_URL;
  if (envBase) {
    return envBase.replace(/\/$/, "");
  }
  const forwardedProto = req.headers.get("x-forwarded-proto");
  const forwardedHost = req.headers.get("x-forwarded-host");
  const host = req.headers.get("host");
  const proto = forwardedProto || "http";
  const resolvedHost = forwardedHost || host;
  if (resolvedHost) {
    return `${proto}://${resolvedHost}`.replace(/\/$/, "");
  }
  return "";
}

async function findAuthUserIdByEmail(admin: ReturnType<typeof createAdminClient>, email: string) {
  const adminAuth = admin.auth.admin as unknown as {
    getUserByEmail?: (value: string) => Promise<{ data: { user: { id: string } | null } | null; error: unknown | null }>;
    listUsers: (value: { page?: number; perPage?: number }) => Promise<{ data: { users: Array<{ id: string; email: string | null }> } | null; error: unknown | null }>;
  };

  if (typeof adminAuth.getUserByEmail === "function") {
    const { data, error } = await adminAuth.getUserByEmail(email);
    if (!error && data?.user?.id) return data.user.id;
  }

  const perPage = 1000;
  for (let page = 1; page <= 50; page += 1) {
    const { data, error } = await adminAuth.listUsers({ page, perPage });
    if (error) return null;
    const users = data?.users ?? [];
    if (!users.length) return null;

    const found = users.find((u) => (u.email ?? "").trim().toLowerCase() === email);
    if (found?.id) return found.id;

    if (users.length < perPage) return null;
  }

  return null;
}

async function findAuthUserEmailById(admin: ReturnType<typeof createAdminClient>, userId: string) {
  const adminAuth = admin.auth.admin as unknown as {
    getUserById?: (value: string) => Promise<{ data: { user: { email: string | null } | null } | null; error: unknown | null }>;
  };

  if (typeof adminAuth.getUserById !== "function") return null;
  const { data, error } = await adminAuth.getUserById(userId);
  if (error) return null;
  return data?.user?.email ? data.user.email.trim().toLowerCase() : null;
}

async function findPlanData(
  admin: ReturnType<typeof createAdminClient>,
  input: { billingEmail: string; companyId: string; userEmail?: string }
) {
  const byEmail = await admin
    .from("users_app")
    .select("*")
    .ilike("email", input.billingEmail)
    .limit(1);

  const byEmailRow = byEmail.data?.[0] ?? null;
  if (!byEmail.error && byEmailRow) return byEmailRow;

  const byId = await admin
    .from("users_app")
    .select("*")
    .eq("id", input.companyId)
    .limit(1);

  const byIdRow = byId.data?.[0] ?? null;
  if (!byId.error && byIdRow) return byIdRow;

  // Fallback: email direto do usuário autenticado (caso billingEmail difira)
  if (input.userEmail && input.userEmail.trim().toLowerCase() !== input.billingEmail.trim().toLowerCase()) {
    const byUser = await admin
      .from("users_app")
      .select("*")
      .ilike("email", input.userEmail)
      .limit(1);

    const byUserRow = byUser.data?.[0] ?? null;
    if (!byUser.error && byUserRow) return byUserRow;
  }

  if (byEmail.error) throw byEmail.error;
  if (byId.error) throw byId.error;
  return null;
}

async function ensureCompanyExistsForContext(ctx: {
  admin: ReturnType<typeof createAdminClient>;
  companyId: string;
  ownerId: string;
  billingEmail: string;
}) {
  const displayName = ctx.billingEmail.split("@")[0]?.trim() || "Empresa";
  const fullInsertPayload: Record<string, unknown> = {
    id: ctx.companyId,
    owner_id: ctx.ownerId,
    billing_email: ctx.billingEmail,
    name: displayName,
  };
  const minimalInsertPayload: Record<string, unknown> = {
    id: ctx.companyId,
    billing_email: ctx.billingEmail,
  };

  const { data: companyRow, error: companyError } = await ctx.admin
    .from("companies")
    .select("id, owner_id, billing_email, name")
    .eq("id", ctx.companyId)
    .maybeSingle();

  if (companyError) throw companyError;

  if (!companyRow) {
    const { error: createError } = await ctx.admin.from("companies").insert(fullInsertPayload);
    if (createError) {
      const { error: createMinimalError } = await ctx.admin.from("companies").insert(minimalInsertPayload);
      if (createMinimalError) throw createError;
    }
    return;
  }

  const patchPayload: Record<string, unknown> = {
    owner_id: ctx.ownerId,
    billing_email: ctx.billingEmail,
    name: displayName,
  };

  /* Esta rota era chamada em toda troca de rota e gravava a empresa sempre,
     mesmo sem nada ter mudado. Agora so escreve quando algum campo difere. */
  const atual = companyRow as { owner_id?: string | null; billing_email?: string | null; name?: string | null };
  if (atual.owner_id === ctx.ownerId && atual.billing_email === ctx.billingEmail && atual.name === displayName) {
    return;
  }

  const { error: patchError } = await ctx.admin
    .from("companies")
    .update(patchPayload)
    .eq("id", ctx.companyId);

  if (patchError) {
    const { error: patchMinimalError } = await ctx.admin
      .from("companies")
      .update({ billing_email: ctx.billingEmail })
      .eq("id", ctx.companyId);
    if (patchMinimalError) throw patchError;
  }
}

async function getAuthContext() {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user || !user.email) {
    return { ok: false as const, response: NextResponse.json({ error: "Não autenticado." }, { status: 401 }) };
  }

  const admin = createAdminClient();
  const { data: membership } = await admin
    .from("company_users")
    .select("company_id,role,active")
    .eq("user_id", user.id)
    .maybeSingle();

  if (membership && membership.active === false) {
    return { ok: false as const, response: NextResponse.json({ error: "Usuário desativado." }, { status: 403 }) };
  }

  let companyId: string | null =
    membership && typeof membership.company_id === "string" && membership.company_id
      ? membership.company_id
      : null;

  let companyOwnerId: string | null = null;
  let ownerEmailFromMembership: string | null = null;
  let subscriptionStatus: string | null = null;
  let subscriptionExpiresAt: string | null = null;
  let billingEmailFromCompany: string | null = null;

  // Para contas que não têm vínculo em company_users (donos antigos),
  // tentamos resolver a empresa pelo campo owner_id em companies.
  if (!companyId) {
    const companyByOwner = await admin
      .from("companies")
      .select("id,billing_email,subscription_status,subscription_expires_at")
      .eq("owner_id", user.id)
      .maybeSingle();

    if (!companyByOwner.error && companyByOwner.data && companyByOwner.data.id) {
      const idValue = companyByOwner.data.id;
      if (typeof idValue === "string" && idValue) {
        companyId = idValue;
      }

      if (companyByOwner.data.billing_email) {
        billingEmailFromCompany = String(companyByOwner.data.billing_email).trim().toLowerCase();
      }
      subscriptionStatus =
        typeof companyByOwner.data.subscription_status === "string"
          ? companyByOwner.data.subscription_status
          : null;
      subscriptionExpiresAt =
        typeof companyByOwner.data.subscription_expires_at === "string"
          ? companyByOwner.data.subscription_expires_at
          : null;
    }
  }

  // Cenário legado extremo: ainda não há registro em companies.
  // Mantemos o fallback para o id do usuário para não quebrar nada.
  if (!companyId) {
    companyId = user.id;
  }

  // Se ainda não carregamos dados de billing/assinatura, buscamos pela companyId final.
  if (!billingEmailFromCompany && !subscriptionStatus && !subscriptionExpiresAt) {
    const companyById = await admin
      .from("companies")
      .select("id,billing_email,subscription_status,subscription_expires_at")
      .eq("id", companyId)
      .maybeSingle();

    if (!companyById.error && companyById.data) {
      if (companyById.data.billing_email) {
        billingEmailFromCompany = String(companyById.data.billing_email).trim().toLowerCase();
      }
      subscriptionStatus =
        typeof companyById.data.subscription_status === "string"
          ? companyById.data.subscription_status
          : null;
      subscriptionExpiresAt =
        typeof companyById.data.subscription_expires_at === "string"
          ? companyById.data.subscription_expires_at
          : null;
    }
  }

  const ownerMembership = await admin
    .from("company_users")
    .select("user_id,email,active")
    .eq("company_id", companyId)
    .eq("role", "owner")
    .maybeSingle();

  if (!ownerMembership.error && ownerMembership.data && ownerMembership.data.active !== false) {
    companyOwnerId = typeof ownerMembership.data.user_id === "string" ? ownerMembership.data.user_id : null;
    ownerEmailFromMembership =
      typeof ownerMembership.data.email === "string"
        ? ownerMembership.data.email.trim().toLowerCase()
        : null;
  }

  const ownerId = companyOwnerId ?? (membership?.role === "owner" ? user.id : null) ?? user.id;
  const ownerEmail =
    ownerId === user.id
      ? user.email
      : ownerEmailFromMembership ?? (await findAuthUserEmailById(admin, ownerId)) ?? user.email;
  const billingEmail = (billingEmailFromCompany ?? ownerEmail ?? user.email).trim().toLowerCase();

  const canManage =
    membership?.role === "owner" ||
    membership?.role === "admin" ||
    ownerId === user.id;

  return {
    ok: true as const,
    admin,
    user,
    companyId,
    ownerId,
    canManage,
    billingEmail,
    subscriptionStatus,
    subscriptionExpiresAt,
  };
}

export async function GET(req: Request) {
  const ctx = await getAuthContext();
  if (!ctx.ok) return ctx.response;

  const mode = new URL(req.url).searchParams.get("mode");
  if (mode === "sales-options") {
    const { data, error } = await ctx.admin
      .from("company_users")
      .select("user_id,email,role,active")
      .eq("company_id", ctx.companyId)
      .eq("active", true)
      .order("created_at", { ascending: true });

    if (error) {
      return NextResponse.json({ error: "Falha ao listar vendedores." }, { status: 500 });
    }

    const users = ((data ?? []) as SalesOptionRow[]).filter((item) => item.active);
    if (!users.some((item) => item.user_id === ctx.ownerId)) {
      users.unshift({
        user_id: ctx.ownerId,
        email: ctx.billingEmail,
        role: "owner",
        active: true,
      });
    }

    return NextResponse.json({
      currentUserId: ctx.user.id,
      users: users.map((item) => ({
        user_id: item.user_id,
        email: item.email,
        role: item.role,
      })),
    });
  }

  let users: CompanyUserRow[] = [];
  if (ctx.canManage) {
    try {
      await ensureCompanyExistsForContext(ctx);
    } catch {
      return NextResponse.json(
        { error: "Falha ao preparar empresa para cadastro de funcionários." },
        { status: 500 },
      );
    }

    const { data, error } = await ctx.admin
      .from("company_users")
      .select("id,company_id,user_id,email,role,permissions,active,created_at,updated_at")
      .eq("company_id", ctx.companyId)
      .order("created_at", { ascending: true });

    if (error) {
      return NextResponse.json({ error: "Falha ao listar funcionários." }, { status: 500 });
    }

    users = (data ?? []) as CompanyUserRow[];
    const ownerUserId = ctx.ownerId;
    const ownerMembership = users.find((item) => item.user_id === ownerUserId);
    const now = new Date().toISOString();
    let ownerChanged = false;

    if (!ownerMembership) {
      const { data: globalMembership, error: globalMembershipError } = await ctx.admin
        .from("company_users")
        .select("id,company_id")
        .eq("user_id", ownerUserId)
        .maybeSingle();

      if (!globalMembershipError && !globalMembership) {
        const { error: insertOwnerError } = await ctx.admin.from("company_users").insert({
          company_id: ctx.companyId,
          user_id: ownerUserId,
          email: ctx.billingEmail,
          role: "owner" as const,
          permissions: {},
          active: true,
          created_at: now,
          updated_at: now,
        });
        ownerChanged = !insertOwnerError;
      } else if (!globalMembershipError && globalMembership && globalMembership.company_id === ctx.companyId) {
        const { error: updateOwnerError } = await ctx.admin
          .from("company_users")
          .update({
            email: ctx.billingEmail,
            role: "owner" as const,
            active: true,
            updated_at: now,
          })
          .eq("id", globalMembership.id);
        ownerChanged = !updateOwnerError;
      }
    } else if (
      ownerMembership.role !== "owner" ||
      ownerMembership.active === false ||
      ownerMembership.email.trim().toLowerCase() !== ctx.billingEmail
    ) {
      const { error: updateOwnerError } = await ctx.admin
        .from("company_users")
        .update({
          email: ctx.billingEmail,
          role: "owner" as const,
          active: true,
          updated_at: now,
        })
        .eq("id", ownerMembership.id);
      ownerChanged = !updateOwnerError;
    }

    if (ownerChanged) {
      const { data: dataAfterOwner, error: errorAfterOwner } = await ctx.admin
        .from("company_users")
        .select("id,company_id,user_id,email,role,permissions,active,created_at,updated_at")
        .eq("company_id", ctx.companyId)
        .order("created_at", { ascending: true });

      if (!errorAfterOwner && dataAfterOwner) {
        users = dataAfterOwner as CompanyUserRow[];
      }
    }
  }

  let planFromBilling: Record<string, unknown> | null = null;
  try {
    planFromBilling = (await findPlanData(ctx.admin, {
      billingEmail: ctx.billingEmail,
      companyId: ctx.ownerId,
      /* O e-mail de quem está logado só serve de reserva para o DONO (cobrança
         cadastrada com outro e-mail). Para funcionário, cair nele mostrava o
         plano da pessoa como se fosse o da empresa. */
      userEmail: ctx.user.id === ctx.ownerId ? ctx.user.email : undefined,
    })) as Record<string, unknown> | null;
  } catch {
    planFromBilling = null;
  }

  const mergedPlan: Record<string, unknown> = { ...(planFromBilling ?? {}) };
  if (!mergedPlan.status && ctx.subscriptionStatus) mergedPlan.status = ctx.subscriptionStatus;
  if (!mergedPlan.expires_at && ctx.subscriptionExpiresAt) mergedPlan.expires_at = ctx.subscriptionExpiresAt;

  const plan = Object.keys(mergedPlan).length ? mergedPlan : null;

  return NextResponse.json({
    company: {
      id: ctx.companyId,
      owner_id: ctx.ownerId,
      billing_email: ctx.billingEmail,
      subscription_status: ctx.subscriptionStatus,
      subscription_expires_at: ctx.subscriptionExpiresAt,
    },
    plan,
    users,
    /* Recursos que ainda estão sendo liberados empresa por empresa. A tela de
       permissões só mostra a permissão de um recurso que a empresa já tem. */
    recursos: {
      assistentes: await assistentesLiberadosAgora([ctx.companyId, ctx.ownerId]),
      /* A área de produtos digitais: o menu lateral também lê daqui. */
      digitais: await digitaisLiberadosAgora([ctx.companyId, ctx.ownerId]),
      /* O KtaloguDesign (beta): o menu e o "Criar banner" do editor da loja leem daqui. */
      design: designLiberado([ctx.companyId, ctx.ownerId]),
    },
  });
}

export async function POST(req: Request) {
  const ctx = await getAuthContext();
  if (!ctx.ok) return ctx.response;

  if (!ctx.canManage) {
    return NextResponse.json({ error: "Sem permissão." }, { status: 403 });
  }

  const body = (await req.json().catch(() => null)) as
    | {
        email?: unknown;
        role?: unknown;
        permissions?: unknown;
      }
    | null;

  const email = typeof body?.email === "string" ? body.email.trim().toLowerCase() : "";
  const role = normalizeMutableRole(body?.role) ?? "viewer";
  const permissions = body?.permissions ?? {};

  if (!email || !isValidEmail(email)) {
    return NextResponse.json({ error: "Email inválido." }, { status: 400 });
  }

  try {
    await ensureCompanyExistsForContext(ctx);
  } catch (e) {
    console.error("Exceção ao preparar empresa para company_users", e);
    return NextResponse.json(
      { error: "Falha ao preparar empresa para cadastro de funcionários." },
      { status: 500 },
    );
  }

  const { data: exists } = await ctx.admin
    .from("company_users")
    .select("id")
    .eq("company_id", ctx.companyId)
    .eq("email", email)
    .maybeSingle();

  if (exists?.id) {
    return NextResponse.json({ error: "Este email já está na empresa." }, { status: 409 });
  }

  let authUserId: string | null = null;
  let createdAuthUser = false;

  const { data: created, error: createError } = await ctx.admin.auth.admin.createUser({
    email,
    email_confirm: true,
  });

  if (created.user?.id) {
    authUserId = created.user.id;
    createdAuthUser = true;
  } else if (createError) {
    const existingId = await findAuthUserIdByEmail(ctx.admin, email);
    if (!existingId) {
      return NextResponse.json({ error: "Falha ao buscar usuário existente." }, { status: 500 });
    }
    authUserId = existingId;
  } else {
    return NextResponse.json({ error: "Falha ao criar usuário de autenticação." }, { status: 500 });
  }

  if (!authUserId) {
    return NextResponse.json({ error: "Falha ao criar usuário de autenticação." }, { status: 500 });
  }

  const { data: existingLink, error: existingLinkError } = await ctx.admin
    .from("company_users")
    .select("id,company_id")
    .eq("user_id", authUserId)
    .maybeSingle();

  if (existingLinkError) {
    if (createdAuthUser) {
      await ctx.admin.auth.admin.deleteUser(authUserId);
    }
    return NextResponse.json({ error: "Falha ao verificar vínculo existente." }, { status: 500 });
  }

  if (existingLink?.id) {
    if (createdAuthUser) {
      await ctx.admin.auth.admin.deleteUser(authUserId);
    }

    if (existingLink.company_id === ctx.companyId) {
      return NextResponse.json({ error: "Este usuário já está na empresa." }, { status: 409 });
    }

    return NextResponse.json({ error: "Este usuário já está vinculado a outra empresa." }, { status: 409 });
  }

  const now = new Date().toISOString();
  const { error: insertError } = await ctx.admin.from("company_users").insert({
    company_id: ctx.companyId,
    user_id: authUserId,
    email,
    role,
    permissions,
    active: true,
    created_at: now,
    updated_at: now,
  });

  if (insertError) {
    // Log técnico no servidor para debug
    // (apenas aparece no console do servidor Next.js / Vercel).
    // Não expõe detalhes sensíveis diretamente para o cliente em produção.
    console.error("Erro ao inserir em company_users", {
      insertError,
      companyId: ctx.companyId,
      authUserId,
      email,
      role,
    });

    if (createdAuthUser) {
      await ctx.admin.auth.admin.deleteUser(authUserId);
    }

    const baseMessage = "Falha ao vincular funcionário à empresa.";

    // Em desenvolvimento, retornamos detalhes extras para facilitar o diagnóstico.
    if (process.env.NODE_ENV !== "production") {
      const extra =
        (insertError.code ? ` Código: ${insertError.code}.` : "") +
        (insertError.message ? ` Detalhe: ${insertError.message}` : "");

      return NextResponse.json(
        {
          error: `${baseMessage}${extra}`,
        },
        { status: 500 },
      );
    }

    return NextResponse.json({ error: baseMessage }, { status: 500 });
  }

  const origin = getResetBaseUrl(req) || new URL(req.url).origin.replace(/\/$/, "");
  const { error: resetError } = await ctx.admin.auth.resetPasswordForEmail(email, {
    redirectTo: `${origin}/auth/callback?next=/reset-password`,
  });

  if (resetError) {
    return NextResponse.json({ error: "Usuário criado, mas não foi possível enviar o reset de senha." }, { status: 500 });
  }

  return NextResponse.json({ ok: true });
}

export async function PATCH(req: Request) {
  const ctx = await getAuthContext();
  if (!ctx.ok) return ctx.response;

  if (!ctx.canManage) {
    return NextResponse.json({ error: "Sem permissão." }, { status: 403 });
  }

  const body = (await req.json().catch(() => null)) as
    | {
        id?: unknown;
        role?: unknown;
        permissions?: unknown;
        active?: unknown;
      }
    | null;

  const id = typeof body?.id === "string" ? body.id : "";
  if (!id) return NextResponse.json({ error: "Campo 'id' é obrigatório." }, { status: 400 });

  const { data: existing, error: existingError } = await ctx.admin
    .from("company_users")
    .select("id,user_id,company_id")
    .eq("id", id)
    .maybeSingle();

  if (existingError || !existing) {
    return NextResponse.json({ error: "Funcionário não encontrado." }, { status: 404 });
  }

  if (existing.company_id !== ctx.companyId) {
    return NextResponse.json({ error: "Acesso negado." }, { status: 403 });
  }

  if (existing.user_id === ctx.user.id) {
    return NextResponse.json({ error: "Você não pode editar seu próprio vínculo aqui." }, { status: 400 });
  }

  const patch: Record<string, unknown> = { updated_at: new Date().toISOString() };

  const role = normalizeMutableRole(body?.role);
  if (role) patch.role = role;
  if (body?.permissions !== undefined) {
    /* Recusar em vez de gravar o que veio: uma chave com erro de digitação era
       aceita e ignorada depois pelo resolvedor, então o admin marcava algo que
       nunca valia e não tinha como saber. */
    const validacao = validarAjustesDePermissao(body.permissions);
    if (!validacao.ok) {
      return NextResponse.json({ error: validacao.erro }, { status: 400 });
    }
    patch.permissions = validacao.ajustes;
  }
  if (typeof body?.active === "boolean") patch.active = body.active;

  const { error: updateError } = await ctx.admin.from("company_users").update(patch).eq("id", id);
  if (updateError) {
    return NextResponse.json({ error: "Falha ao atualizar funcionário." }, { status: 500 });
  }

  /* Quem saiu do ar ou perdeu a permissão de usar assistentes tem as chaves e
     conexões desligadas agora. Sem isto, elas ficavam paradas e voltavam a
     valer no dia em que a permissão voltasse. */
  const { data: depois } = await ctx.admin.from("company_users").select("user_id,role,permissions,active").eq("id", id).maybeSingle();
  const vinculo = depois as { user_id?: string | null; role?: string | null; permissions?: unknown; active?: boolean | null } | null;
  if (
    vinculo?.user_id &&
    (vinculo.active === false || !canCompanyRole((vinculo.role ?? "viewer") as Parameters<typeof canCompanyRole>[0], vinculo.permissions, "company.assistants.manage"))
  ) {
    await revogarAcessosDosAssistentes(ctx.admin, { companyId: existing.company_id, usuarioId: vinculo.user_id, por: ctx.user.id });
  }

  return NextResponse.json({ ok: true });
}

export async function DELETE(req: Request) {
  const ctx = await getAuthContext();
  if (!ctx.ok) return ctx.response;

  if (!ctx.canManage) {
    return NextResponse.json({ error: "Sem permissão." }, { status: 403 });
  }

  const body = (await req.json().catch(() => null)) as { id?: unknown } | null;
  const id = typeof body?.id === "string" ? body.id : "";
  if (!id) return NextResponse.json({ error: "Campo 'id' é obrigatório." }, { status: 400 });

  const { data: existing, error: existingError } = await ctx.admin
    .from("company_users")
    .select("id,user_id,company_id")
    .eq("id", id)
    .maybeSingle();

  if (existingError || !existing) {
    return NextResponse.json({ error: "Funcionário não encontrado." }, { status: 404 });
  }

  if (existing.company_id !== ctx.companyId) {
    return NextResponse.json({ error: "Acesso negado." }, { status: 403 });
  }

  if (existing.user_id === ctx.user.id) {
    return NextResponse.json({ error: "Você não pode remover a si mesmo." }, { status: 400 });
  }

  const employeeUserId = typeof existing.user_id === "string" ? existing.user_id : "";

  const { error: deleteError } = await ctx.admin.from("company_users").delete().eq("id", id);
  if (deleteError) {
    return NextResponse.json({ error: "Falha ao remover funcionário." }, { status: 500 });
  }

  // Limpar perfil e conta auth do funcionário removido
  if (employeeUserId) {
    // Remove employee_profiles (ignora erro se não existir)
    await ctx.admin
      .from("employee_profiles")
      .delete()
      .eq("user_id", employeeUserId)
      .then(() => {});

    // Remove a conta de autenticação para evitar que o ex-funcionário
    // faça login novamente como uma conta "dono" fantasma
    try {
      await ctx.admin.auth.admin.deleteUser(employeeUserId);
    } catch (e) {
      console.error("Aviso: falha ao remover conta auth do funcionário", employeeUserId, e);
    }
  }

  return NextResponse.json({ ok: true });
}
