import { MigrationInterface, QueryRunner } from 'typeorm';

/** Cash collection for MD — one row per stamp. Additional Cost stays on booking_cash_collections. */
export class MdCashCollections1786700000000 implements MigrationInterface {
  name = 'MdCashCollections1786700000000';

  public async up(qr: QueryRunner): Promise<void> {
    await qr.query(`
      CREATE TABLE IF NOT EXISTS "md_cash_collections" (
        "id" uuid NOT NULL DEFAULT gen_random_uuid(),
        "tenant_id" uuid NOT NULL,
        "booking_id" uuid NOT NULL,
        "currency_id" uuid NOT NULL,
        "amount" numeric(12,2) NOT NULL,
        "status" varchar(20) NOT NULL,
        "collected_by_type" varchar(20) NOT NULL,
        "collector_name" varchar(255),
        "supplier_id" uuid,
        "driver_id" uuid,
        "collected_at" timestamptz,
        "notes" text,
        "created_by" uuid,
        "updated_by" uuid,
        "created_at" timestamptz NOT NULL DEFAULT now(),
        "updated_at" timestamptz NOT NULL DEFAULT now(),
        "is_deleted" boolean NOT NULL DEFAULT false,
        CONSTRAINT "pk_md_cash_collections" PRIMARY KEY ("id"),
        CONSTRAINT "fk_md_cash_booking" FOREIGN KEY ("booking_id") REFERENCES "bookings"("id") ON DELETE CASCADE,
        CONSTRAINT "fk_md_cash_currency" FOREIGN KEY ("currency_id") REFERENCES "currencies"("id"),
        CONSTRAINT "fk_md_cash_supplier" FOREIGN KEY ("supplier_id") REFERENCES "suppliers"("id"),
        CONSTRAINT "fk_md_cash_driver" FOREIGN KEY ("driver_id") REFERENCES "drivers"("id"),
        CONSTRAINT "chk_md_cash_status" CHECK ("status" IN ('PENDING','COLLECTED')),
        CONSTRAINT "chk_md_cash_amount_positive" CHECK ("amount" > 0),
        CONSTRAINT "chk_md_cash_collected_by" CHECK (
          (
            "collected_by_type" = 'OWN'
            AND "collector_name" IS NOT NULL
            AND "supplier_id" IS NULL
            AND "driver_id" IS NULL
          )
          OR (
            "collected_by_type" = 'SUPPLIER'
            AND "collector_name" IS NULL
            AND "supplier_id" IS NOT NULL
            AND "driver_id" IS NOT NULL
          )
        )
      )
    `);
    await qr.query(`
      CREATE INDEX IF NOT EXISTS "ix_md_cash_tenant_booking"
        ON "md_cash_collections" ("tenant_id", "booking_id")
        WHERE "is_deleted" = false
    `);
  }

  public async down(qr: QueryRunner): Promise<void> {
    await qr.query(`DROP TABLE IF EXISTS "md_cash_collections"`);
  }
}
