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

export const runtime = "nodejs";

/**
 * POST /api/system/reset
 *
 * Zera ABSOLUTAMENTE TUDO do sistema (ou módulos específicos) para o tenant atual.
 *
 * Somente o OWNER (dono da conta) pode executar.
 */
export async function POST(req: Request) {
  try {
    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 (!canManageFinancialCritical(ctx, user.id)) {
      return NextResponse.json(
        { error: "Apenas administradores podem realizar esta ação." },
        { status: 403 }
      );
    }

    const body = await req.json().catch(() => null);
    const confirmWord = (body as { confirm?: string } | null)?.confirm;
    const modules = (body as { modules?: string[] } | null)?.modules || [];

    if (confirmWord !== "APAGAR") {
      return NextResponse.json({ error: "Confirmação inválida." }, { status: 400 });
    }

    const tenantIds = ctx.tenantIds?.length ? ctx.tenantIds : [user.id];
    const companyId = ctx.companyId;
    const log: string[] = [];

    const shouldWipe = (mod: string) => modules.includes("all") || modules.includes(mod);

    // Se a lista de módulos for vazia e não for "all", encerra
    if (modules.length === 0) {
      return NextResponse.json({ error: "Nenhum módulo selecionado." }, { status: 400 });
    }

    // ---------------------------------------------------------------
    // Helpers
    // ---------------------------------------------------------------
    const adminClient = createAdminClient();

    const isMissingTableOrColumn = (msg?: string) => {
      if (!msg) return false;
      const lower = msg.toLowerCase();
      return lower.includes("does not exist") || lower.includes("could not find the table") || lower.includes("in the schema");
    };

    const wipeByUser = async (table: string) => {
      for (const tid of tenantIds) {
        try {
          const { error } = await adminClient.from(table).delete().eq("user_id", tid);
          if (error && !isMissingTableOrColumn(error.message)) {
            log.push(`${table}/user_id: ${error.message}`);
          }
        } catch (err: unknown) {
          const errMsg = err instanceof Error ? err.message : String(err);
          if (errMsg.toLowerCase().includes("fetch")) log.push(`${table}/user_id: Supabase Network Error/Timeout`);
        }
      }
    };

    const wipeByCompany = async (table: string) => {
      try {
        const { error } = await adminClient.from(table).delete().eq("company_id", companyId);
        if (error && !isMissingTableOrColumn(error.message)) {
          log.push(`${table}/company_id: ${error.message}`);
        }
      } catch (err: unknown) {
        const errMsg = err instanceof Error ? err.message : String(err);
        if (errMsg.toLowerCase().includes("fetch")) log.push(`${table}/company_id: Supabase Network Error/Timeout`);
      }
    };

    const wipeByProfile = async (table: string) => {
      try {
        const { error } = await adminClient.from(table).delete().eq("profile_id", user!.id);
        if (error && !isMissingTableOrColumn(error.message)) {
          log.push(`${table}/profile_id: ${error.message}`);
        }
      } catch { /* table might not exist */ }
    };

    const wipeByIds = async (table: string, column: string, ids: string[]) => {
      if (ids.length === 0) return;
      const chunkSize = 500;
      for (let i = 0; i < ids.length; i += chunkSize) {
        const chunk = ids.slice(i, i + chunkSize);
        try {
          const { error } = await adminClient.from(table).delete().in(column, chunk);
          if (error && !isMissingTableOrColumn(error.message)) {
            log.push(`${table}/${column}: ${error.message}`);
          }
        } catch { /* ignore */ }
      }
    };

    const collectIds = async (table: string, filterCol: string, filterVals: string[], idCol = "id"): Promise<string[]> => {
      const allIds: string[] = [];
      for (const val of filterVals) {
        try {
          const { data, error } = await adminClient.from(table).select(idCol).eq(filterCol, val);
          if (!error && Array.isArray(data)) {
            allIds.push(
              ...data
                .map((row) => {
                  const record = row as unknown as Record<string, unknown>;
                  return String(record[idCol]);
                })
                .filter(Boolean)
            );
          }
        } catch { /* ignore */ }
      }
      return allIds;
    };

    // ================================================================
    // 1. Coletar IDs das tabelas pai antes de apagar
    // ================================================================
    const [orderIds, quoteIds, productIds] = await Promise.all([
      shouldWipe("orders") || shouldWipe("financial") ? collectIds("orders", "user_id", tenantIds) : Promise.resolve([]),
      shouldWipe("quotes") ? collectIds("quotes", "user_id", tenantIds) : Promise.resolve([]),
      shouldWipe("products") ? collectIds("products", "user_id", tenantIds) : Promise.resolve([])
    ]);

    // ================================================================
    // 2 a 4. COMISSÕES, FINANÇAS E PDV (Nível mais profundo)
    // ================================================================
    const cleanupTier1 = [];
    if (shouldWipe("commissions")) {
      cleanupTier1.push(
        wipeByCompany("commission_audit_log"),
        wipeByCompany("commission_statement_items"),
        wipeByCompany("commission_events"),
        wipeByCompany("commission_payouts")
      );
    }
    if (shouldWipe("financial")) {
      cleanupTier1.push(
        wipeByUser("transactions"),
        wipeByCompany("transactions"),
        wipeByUser("payments"),
        wipeByCompany("payments"),
        wipeByCompany("receivable_receipts"),
        wipeByCompany("accounts_receivable"),
        wipeByCompany("cash_flow"),
        wipeByCompany("payment_links")
      );
      if (orderIds.length > 0) cleanupTier1.push(wipeByIds("payments", "order_id", orderIds));
    }
    if (shouldWipe("payables")) {
      cleanupTier1.push(wipeByUser("accounts_payable"), wipeByCompany("accounts_payable"));
    }
    if (shouldWipe("pdv")) {
      cleanupTier1.push(
        wipeByUser("pdv_cash_movements"),
        wipeByUser("pdv_cash_sessions"),
        wipeByCompany("pdv_cash_movements"),
        wipeByCompany("pdv_cash_sessions")
      );
    }
    await Promise.all(cleanupTier1);

    if (shouldWipe("commissions")) {
      await Promise.all([
        wipeByCompany("commission_rules"),
        wipeByCompany("commission_plan_assignments"),
        wipeByCompany("commission_plan_versions"),
        wipeByCompany("commission_plans"),
        wipeByCompany("commission_periods"),
        wipeByCompany("commission_payout_profiles")
      ]);
    }

    // ================================================================
    // 5 a 8. PEDIDOS, ORÇAMENTOS, PRODUTOS, CATÁLOGO
    // ================================================================
    const cleanupTier2 = [];
    if (shouldWipe("orders") && orderIds.length > 0) {
      cleanupTier2.push(wipeByIds("order_history", "order_id", orderIds), wipeByIds("order_items", "order_id", orderIds));
    }
    if (shouldWipe("quotes") && quoteIds.length > 0) {
      cleanupTier2.push(wipeByIds("quote_item_arts", "quote_id", quoteIds), wipeByIds("quote_items", "quote_id", quoteIds));
    }
    if (shouldWipe("catalog")) {
      cleanupTier2.push(
        wipeByUser("catalog_section_products"),
        wipeByUser("catalog_sections"),
        /* Páginas extras (as seções delas vão junto) e o menu/rodapé próprios. */
        wipeByUser("catalog_paginas"),
        wipeByUser("catalog_navegacao"),
        wipeByUser("catalog_coupons"),
        wipeByUser("catalog_story_items"),
        wipeByUser("catalog_story_groups"),
        wipeByUser("catalog_banners"),
        wipeByUser("catalog_orders"),
        wipeByUser("catalog_events"),
        wipeByProfile("profile_custom_domains")
      );
    }
    if (shouldWipe("products") && productIds.length > 0) {
      cleanupTier2.push(
        wipeByIds("product_images", "product_id", productIds),
        wipeByIds("product_variants", "product_id", productIds),
        wipeByIds("product_materials", "product_id", productIds),
        wipeByIds("product_processes", "product_id", productIds)
      );
    }
    await Promise.all(cleanupTier2);

    const cleanupTier3 = [];
    if (shouldWipe("orders")) cleanupTier3.push(wipeByUser("orders"));
    if (shouldWipe("quotes")) cleanupTier3.push(wipeByUser("quotes"));
    if (shouldWipe("products")) cleanupTier3.push(wipeByUser("products"));
    // ================================================================
    // 9 a 14. RESTANTE (PRODUÇÃO, CLIENTES, FORNECEDORES, ETC)
    // ================================================================
    if (shouldWipe("production")) {
      cleanupTier3.push(
        wipeByUser("materials"), wipeByUser("machines"), wipeByUser("labor_roles"),
        wipeByCompany("materials"), wipeByCompany("machines"), wipeByCompany("labor_roles")
      );
    }
    if (shouldWipe("clients")) cleanupTier3.push(wipeByUser("clients"));
    if (shouldWipe("categories")) cleanupTier3.push(wipeByUser("categories"));
    if (shouldWipe("bank_accounts")) cleanupTier3.push(wipeByCompany("bank_accounts"), wipeByUser("bank_accounts"));
    if (shouldWipe("suppliers")) {
      cleanupTier3.push(
        wipeByUser("fornecedor_xbz_pedidos"), wipeByUser("fornecedor_xbz_logs"), wipeByUser("fornecedor_xbz_transportadoras"),
        wipeByUser("fornecedor_xbz_produtos"), wipeByUser("fornecedor_xbz"), wipeByUser("integrations"), wipeByCompany("integrations")
      );
    }
    if (shouldWipe("employees")) {
      cleanupTier3.push(wipeByUser("employee_profiles"), wipeByCompany("employee_profiles"));
    }
    await Promise.all(cleanupTier3);

    // ================================================================
    // 15. STORAGE — Limpar TODAS as imagens (Paralelizado)
    // ================================================================
    if (shouldWipe("storage")) {
      const storageBuckets = ["products", "quote-arts"];
      const allFolders = [...tenantIds];
      for (const tid of tenantIds) {
        allFolders.push(`logos/${tid}`, `arts/${tid}`, `${tid}/logos`, `${tid}/arts`);
      }

      await Promise.all(storageBuckets.flatMap(bucket => 
        allFolders.map(async (folder) => {
          try {
            const { data: files } = await supabase.storage.from(bucket).list(folder, { limit: 1000 });
            if (files && files.length > 0) {
              const filePaths = files.filter(f => f.name).map(f => `${folder}/${f.name}`);
              if (filePaths.length > 0) await supabase.storage.from(bucket).remove(filePaths);

              // Subpastas
              const subfolders = files.filter(f => !f.metadata);
              await Promise.all(subfolders.map(async (sub) => {
                try {
                  const subPath = `${folder}/${sub.name}`;
                  const { data: subFiles } = await supabase.storage.from(bucket).list(subPath, { limit: 1000 });
                  if (subFiles && subFiles.length > 0) {
                    const subPaths = subFiles.map(sf => `${subPath}/${sf.name}`);
                    await supabase.storage.from(bucket).remove(subPaths);
                  }
                } catch { /* ignore */ }
              }));
            }
          } catch { /* ignore */ }
        })
      ));
    }

    // ================================================================
    // 16. RESETAR TUDO DO PROFILE (Settings)
    // ================================================================
    if (shouldWipe("settings")) {
      const profileReset: Record<string, unknown> = {
        // --- Dados da empresa ---
        logo_url: null,
        store_name: null,
        cnpj: null,
        phone: null,
        company_whatsapp: null,
        address_zip: null,
        address_street: null,
        address_number: null,
        address_complement: null,
        address_neighborhood: null,
        address_city: null,
        address_state: null,
        address: null,
        company_phone: null,
        // --- Catálogo visual ---
        catalog_name: null,
        catalog_logo_url: null,
        primary_color: null,
        catalog_footer_color: null,
        catalog_slogan: null,
        catalog_show_name_in_header: null,
        catalog_show_slogan_in_header: null,
        catalog_show_document: null,
        catalog_name_color: null,
        catalog_slogan_color: null,
        catalog_logo_effect_enabled: null,
        catalog_logo_effect: null,
        catalog_logo_effect_speed: null,
        catalog_logo_effect_intensity: null,
        // --- Catálogo SEO ---
        catalog_meta_title: null,
        catalog_meta_description: null,
        catalog_meta_keywords: null,
        catalog_og_title: null,
        catalog_og_description: null,
        catalog_og_image_url: null,
        catalog_favicon_url: null,
        catalog_twitter_handle: null,
        catalog_noindex: null,
        // --- Catálogo redes sociais ---
        social_facebook: null,
        social_instagram: null,
        social_twitter: null,
        social_linkedin: null,
        social_youtube: null,
        // --- WhatsApp ---
        whatsapp: null,
        // --- Kanban de produção ---
        production_kanban_columns: null,
        production_kanban_archive_enabled: null,
        production_kanban_archive_days: null,
        production_kanban_archive_mode: null,
        // --- Timestamp ---
        updated_at: new Date().toISOString(),
      };

      // Atualizar com retry removendo colunas que não existem no schema ou violam NOT NULL
      let lastError: unknown = null;
      for (let attempt = 0; attempt < 30; attempt++) {
        const { error } = await supabase.from("profiles").update(profileReset).eq("id", user.id);
        if (!error) {
          lastError = null;
          break;
        }
        lastError = error;
        const msg = String((error as { message?: unknown } | null)?.message ?? JSON.stringify(error));
        const matchMissing = msg.match(/column ["']?([a-zA-Z0-9_]+)["']? .*does not exist/i);
        const matchNotNull = msg.match(/column ["']?([a-zA-Z0-9_]+)["']? .*violates not-null/i);
        const badCol = matchMissing?.[1] || matchNotNull?.[1];

        if (!badCol || !(badCol in profileReset)) break;
        delete profileReset[badCol];
      }

      if (lastError) {
        const msg = lastError instanceof Error 
          ? lastError.message 
          : (typeof lastError === "object" ? JSON.stringify(lastError) : String(lastError));
        log.push(`profile reset: ${msg}`);
      }
    }

    /* Produtos, catálogo e perfil podem ter ido embora: a loja não pode
       continuar mostrando, por dois minutos, o que já não existe. */
    avisarLoja(user.id, req);

    if (log.length > 0) {
      console.warn("System reset warnings:", log);

      const mapFriendlyName = (text: string) => {
        const lower = text.toLowerCase();
        if (lower.includes("transaction") || lower.includes("payment")) return "Transações financeiras e pagamentos";
        if (lower.includes("payables")) return "Contas a pagar";
        if (lower.includes("order")) return "Pedidos, itens e histórico";
        if (lower.includes("quote")) return "Orçamentos e artes";
        if (lower.includes("product")) return "Produtos, imagens e galeria";
        if (lower.includes("client")) return "Clientes";
        if (lower.includes("commissions")) return "Comissões, planos e eventos";
        if (lower.includes("pdv")) return "PDV (sessões de caixa)";
        if (lower.includes("catalog")) return "Catálogo";
        if (lower.includes("bank_accounts")) return "Contas bancárias";
        return null;
      };

      const friendlyDetails = log.map(err => {
        if (err.includes("violates foreign key constraint")) {
          const tableMatch = err.match(/on table ["']?([a-zA-Z0-9_]+)["']?/i);
          const tableName = tableMatch ? tableMatch[1] : err;
          const friendly = mapFriendlyName(tableName);
          if (friendly) {
            return `Conflito de dependência. MARQUE TAMBÉM: ${friendly}`;
          }
          return `Dependência bloqueada na tabela: ${tableName}`;
        }
        return "Erro ao limpar: " + (err.length > 80 ? err.substring(0, 80) + "..." : err);
      });

      // Remove duplicatas para a mensagem ficar limpa
      const uniqueDetails = Array.from(new Set(friendlyDetails));

      return NextResponse.json({ 
        error: "O sistema empediu a exclusão porque há registros entrelaçados. Marque as opções complementares na lista e tente novamente:",
        details: uniqueDetails
      }, { status: 400 });
    }

    return NextResponse.json({
      success: true,
    });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : "Erro interno no servidor";
    console.error("Erro geral ao zerar sistema:", err);
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
