import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Cash Held at destination (docs/cash-held-at-destination-plan.md).
 *
 * - md_cash_collections: `counts_as_held` (default false, so existing
 *   stamps are NOT carried into balances — client Q8) + `holder_key`.
 * - cash_held_movements: append-only ledger of what holders do with
 *   the cash (pay supplier, customer use, transfer, return).
 *
 * Permission rows for the new `cash_held` module are created on boot
 * by TenantService.onModuleInit (Admin = delete, other seeded roles =
 * none, custom roles = none).
 */
export class CashHeldLedger1788500000000 implements MigrationInterface {
  name = 'CashHeldLedger1788500000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE "md_cash_collections"
        ADD COLUMN IF NOT EXISTS "counts_as_held" boolean NOT NULL DEFAULT false,
        ADD COLUMN IF NOT EXISTS "holder_key" varchar(300)
    `);
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS "cash_held_movements" (
        "id" uuid NOT NULL DEFAULT gen_random_uuid(),
        "tenant_id" uuid NOT NULL,
        "created_by" uuid,
        "updated_by" uuid,
        "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
        "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
        "is_deleted" boolean NOT NULL DEFAULT false,
        "holder_key" varchar(300) NOT NULL,
        "holder_type" varchar(20) NOT NULL,
        "collector_name" varchar(255),
        "supplier_id" uuid,
        "driver_id" uuid,
        "movement_type" varchar(20) NOT NULL,
        "direction" varchar(3) NOT NULL,
        "currency_id" uuid NOT NULL REFERENCES "currencies"("id"),
        "amount" decimal(12,2) NOT NULL,
        "movement_date" date NOT NULL,
        "booking_id" uuid,
        "related_movement_id" uuid,
        "supplier_payout_id" uuid,
        "bank_account_id" uuid,
        "ref_no" varchar(100),
        "notes" text,
        CONSTRAINT "pk_cash_held_movements" PRIMARY KEY ("id"),
        CONSTRAINT "chk_cash_held_amount_positive" CHECK ("amount" > 0),
        CONSTRAINT "chk_cash_held_type" CHECK ("movement_type" IN ('TRANSFER_IN','TRANSFER_OUT','PAID_SUPPLIER','CUSTOMER_USE','RETURNED')),
        CONSTRAINT "chk_cash_held_holder" CHECK (
          ("holder_type" = 'OWN' AND "collector_name" IS NOT NULL AND "supplier_id" IS NULL AND "driver_id" IS NULL)
          OR ("holder_type" = 'SUPPLIER' AND "collector_name" IS NULL AND "supplier_id" IS NOT NULL AND "driver_id" IS NOT NULL)
        )
      )
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "ix_cash_held_tenant_holder"
        ON "cash_held_movements" ("tenant_id", "holder_key", "currency_id")
        WHERE "is_deleted" = false
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE IF EXISTS "cash_held_movements"`);
    await queryRunner.query(`
      ALTER TABLE "md_cash_collections"
        DROP COLUMN IF EXISTS "holder_key",
        DROP COLUMN IF EXISTS "counts_as_held"
    `);
  }
}
