-- Wave 11.B+: documents hub split + auto-filed client folders.
-- Adds system-managed folder lifecycle columns to document_folders
-- (Clients/Companies/Yachts roots + per-entity subfolders) and the
-- folder_id pointer to files. Backfill (ensureSystemRoots + per-
-- entity subfolders + files.folder_id from entity FKs) runs as a
-- separate deploy step - see scripts/backfill-document-folders.ts.
-- Idempotent - safe to re-run.

-- ─── document_folders: lifecycle columns ──────────────────────────────────
ALTER TABLE "document_folders"
  ADD COLUMN IF NOT EXISTS "system_managed" boolean NOT NULL DEFAULT false,
  ADD COLUMN IF NOT EXISTS "entity_type" text,
  ADD COLUMN IF NOT EXISTS "entity_id" text,
  ADD COLUMN IF NOT EXISTS "archived_at" timestamp with time zone;

-- Shape guard: system_managed=true implies a known shape.
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint WHERE conname = 'chk_system_folder_shape'
  ) THEN
    ALTER TABLE "document_folders"
      ADD CONSTRAINT "chk_system_folder_shape" CHECK (
        NOT system_managed
        OR entity_type = 'root'
        OR (entity_type IN ('client','company','yacht') AND entity_id IS NOT NULL)
      );
  END IF;
END $$;

-- Partial unique index: one subfolder per (port, entity_type, entity_id).
CREATE UNIQUE INDEX IF NOT EXISTS "uniq_document_folders_entity"
  ON "document_folders" ("port_id", "entity_type", "entity_id")
  WHERE "entity_id" IS NOT NULL;

-- ─── files: folder pointer ────────────────────────────────────────────────
ALTER TABLE "files"
  ADD COLUMN IF NOT EXISTS "folder_id" text REFERENCES "document_folders" ("id")
    ON DELETE SET NULL;

CREATE INDEX IF NOT EXISTS "idx_files_folder" ON "files" ("folder_id");
CREATE INDEX IF NOT EXISTS "idx_files_port_folder" ON "files" ("port_id", "folder_id");
