-- 0090_bulk_import.sql
--
-- Bulk CSV/XLSX importer (docs/superpowers/specs/2026-06-01-bulk-import-design.md).
-- Three new tables, no changes to entity tables: a per-import batch header,
-- a per-row action/undo ledger, and saved column mappings. All port-scoped.
-- IDs are app-generated (crypto.randomUUID via Drizzle $defaultFn), so no DB
-- default on the PK columns — matches the rest of the schema.

CREATE TABLE import_batches (
  id              text PRIMARY KEY,
  port_id         text NOT NULL REFERENCES ports(id) ON DELETE CASCADE,
  entity_type     text NOT NULL,
  filename        text NOT NULL,
  storage_key     text,
  status          text NOT NULL DEFAULT 'uploaded',
  conflict_policy text NOT NULL DEFAULT 'skip-matches',
  mapping_json    jsonb,
  total_rows      integer NOT NULL DEFAULT 0,
  inserted        integer NOT NULL DEFAULT 0,
  updated         integer NOT NULL DEFAULT 0,
  skipped         integer NOT NULL DEFAULT 0,
  errored         integer NOT NULL DEFAULT 0,
  created_by      text NOT NULL,
  created_at      timestamptz NOT NULL DEFAULT now(),
  completed_at    timestamptz
);
CREATE INDEX idx_import_batches_port ON import_batches (port_id, created_at DESC);

CREATE TABLE import_batch_rows (
  id          text PRIMARY KEY,
  batch_id    text NOT NULL REFERENCES import_batches(id) ON DELETE CASCADE,
  row_number  integer NOT NULL,
  action      text NOT NULL,
  entity_id   text,
  error       text
);
CREATE INDEX idx_import_batch_rows_batch ON import_batch_rows (batch_id, row_number);
-- Undo walks only the rows a batch INSERTED; partial index keeps that scan tight.
CREATE INDEX idx_import_batch_rows_inserted ON import_batch_rows (batch_id) WHERE action = 'inserted';

CREATE TABLE import_mappings (
  id           text PRIMARY KEY,
  port_id      text NOT NULL REFERENCES ports(id) ON DELETE CASCADE,
  entity_type  text NOT NULL,
  name         text NOT NULL,
  mapping_json jsonb NOT NULL,
  created_by   text NOT NULL,
  created_at   timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX uniq_import_mappings_name ON import_mappings (port_id, entity_type, name);
