/**
 * Bulk import (CDP-008): CSV/XLSX parsed in the browser, mapped to fields, previewed for duplicates, then sent in
 * chunks of ≤1,000 rows. A 50,000-row import completes with a downloadable error report.
 */
import { and, eq, inArray, or } from "drizzle-orm";
import { schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import { identitiesFrom, upsertContact } from "./contacts";

export type ImportRow = Record<string, string>;
export type Mapping = Record<string, string>; // column -> field (first_name, last_name, name, email, phone, city, project, source, tags, custom.<key>)

export function mapRow(row: ImportRow, mapping: Mapping) {
  const out: Record<string, any> = { customFields: {} };
  for (const [col, field] of Object.entries(mapping)) {
    const v = row[col]?.toString().trim();
    if (!v || !field || field === "skip") continue;
    if (field.startsWith("custom.")) out.customFields[field.slice(7)] = v;
    else if (field === "tags") out.tags = v.split(/[;,]/).map((t) => t.trim()).filter(Boolean);
    else if (field === "first_name") out.firstName = v;
    else if (field === "last_name") out.lastName = v;
    else out[field] = v;
  }
  return out;
}

/** Dedupe preview: how many rows match existing contacts or each other. */
export async function previewImport(ctx: Ctx, rows: ImportRow[], mapping: Mapping) {
  const cc = ctx.workspace.settings?.defaultCountryCode ?? "880";
  const seen = new Map<string, number>();
  let duplicatesInFile = 0, invalid = 0;
  const allIds: { type: string; value: string }[] = [];
  rows.forEach((r, i) => {
    const m = mapRow(r, mapping);
    const ids = identitiesFrom(m, cc);
    if (!ids.length && !m.name && !m.firstName) invalid++;
    let dup = false;
    for (const id of ids) {
      const k = `${id.type}:${id.value}`;
      if (seen.has(k)) dup = true;
      else seen.set(k, i);
      allIds.push(id);
    }
    if (dup) duplicatesInFile++;
  });
  let existing = 0;
  for (let i = 0; i < allIds.length; i += 500) {
    const chunk = allIds.slice(i, i + 500);
    const found = await ctx.db.select({ c: schema.identities.contactId }).from(schema.identities).where(and(eq(schema.identities.workspaceId, ctx.workspace.id), or(...chunk.map((x) => and(eq(schema.identities.type, x.type), eq(schema.identities.valueNormalized, x.value))))));
    existing += new Set(found.map((f) => f.c)).size;
  }
  return { rows: rows.length, invalid, duplicatesInFile, matchesExisting: existing, willCreate: Math.max(0, rows.length - invalid - duplicatesInFile - existing) };
}

/** Process a chunk synchronously (called per chunk from the UI so progress is visible). */
export async function importChunk(ctx: Ctx, rows: ImportRow[], mapping: Mapping, opts: { offset: number; tags?: string[]; source?: string }) {
  const errors: { row: number; error: string }[] = [];
  let created = 0, updated = 0;
  for (let i = 0; i < rows.length; i++) {
    try {
      const m = mapRow(rows[i]!, mapping);
      m.tags = [...(m.tags ?? []), ...(opts.tags ?? [])];
      m.source = m.source ?? opts.source ?? "import";
      const r = await upsertContact(ctx, m, { source: "import", skipJourneys: true });
      if (r.created) created++; else updated++;
    } catch (e) {
      errors.push({ row: opts.offset + i + 2, error: e instanceof Error ? e.message : String(e) });
    }
  }
  return { created, updated, errors };
}

export async function processImport(ctx: Ctx, p: Record<string, unknown>) {
  return importChunk(ctx, p.rows as ImportRow[], p.mapping as Mapping, { offset: Number(p.offset ?? 0), tags: p.tags as string[] | undefined });
}

export { inArray };
