-- Rework Terms & Conditions (issue #11 follow-up): the fixed TermsCategory ENUM
-- becomes a user-defined TermsCategory TABLE; clauses gain isDefault/sortOrder;
-- PurchaseOrder gains a JSON `terms` snapshot. Existing enum-based clauses are
-- migrated onto the new category rows. Forward migration (the original
-- 20260624140000 migration is already released and stays untouched).

-- Free the "TermsCategory" name (a table and an enum type cannot coexist).
ALTER TYPE "TermsCategory" RENAME TO "TermsCategory_old";

-- New category table.
CREATE TABLE "TermsCategory" (
    "id" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "sortOrder" INTEGER NOT NULL DEFAULT 0,
    "isActive" BOOLEAN NOT NULL DEFAULT true,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "TermsCategory_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "TermsCategory_name_key" ON "TermsCategory"("name");

INSERT INTO "TermsCategory" ("id", "name", "sortOrder", "updatedAt") VALUES
  ('tcat_general',  'General',               0, CURRENT_TIMESTAMP),
  ('tcat_delivery', 'Delivery',              1, CURRENT_TIMESTAMP),
  ('tcat_dispatch', 'Dispatch Instructions', 2, CURRENT_TIMESTAMP),
  ('tcat_inspect',  'Inspection',            3, CURRENT_TIMESTAMP),
  ('tcat_transit',  'Transit Insurance',     4, CURRENT_TIMESTAMP),
  ('tcat_payment',  'Payment Terms',         5, CURRENT_TIMESTAMP),
  ('tcat_others',   'Others',                6, CURRENT_TIMESTAMP);

-- New clause columns.
ALTER TABLE "TermsCondition" ADD COLUMN "categoryId" TEXT;
ALTER TABLE "TermsCondition" ADD COLUMN "isDefault" BOOLEAN NOT NULL DEFAULT false;
ALTER TABLE "TermsCondition" ADD COLUMN "sortOrder" INTEGER NOT NULL DEFAULT 0;

-- Migrate existing clauses from the enum onto category rows.
UPDATE "TermsCondition" SET "categoryId" = CASE "category"::text
  WHEN 'DELIVERY'          THEN 'tcat_delivery'
  WHEN 'DISPATCH'          THEN 'tcat_dispatch'
  WHEN 'INSPECTION'        THEN 'tcat_inspect'
  WHEN 'TRANSIT_INSURANCE' THEN 'tcat_transit'
  WHEN 'PAYMENT_TERMS'     THEN 'tcat_payment'
END;

-- The original seed clauses become the PO defaults.
UPDATE "TermsCondition" SET "isDefault" = true
  WHERE "id" IN ('tcseed_delivery','tcseed_dispatch','tcseed_inspect','tcseed_transit','tcseed_payment');

-- Drop the old enum column + type now that data is migrated.
DROP INDEX "TermsCondition_category_idx";
ALTER TABLE "TermsCondition" DROP COLUMN "category";
DROP TYPE "TermsCategory_old";

-- Enforce the relation.
ALTER TABLE "TermsCondition" ALTER COLUMN "categoryId" SET NOT NULL;
CREATE INDEX "TermsCondition_categoryId_idx" ON "TermsCondition"("categoryId");
ALTER TABLE "TermsCondition" ADD CONSTRAINT "TermsCondition_categoryId_fkey" FOREIGN KEY ("categoryId") REFERENCES "TermsCategory"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- Seed the previously-fixed boilerplate lines as default "General" clauses.
INSERT INTO "TermsCondition" ("id", "categoryId", "text", "isDefault", "sortOrder", "updatedAt") VALUES
  ('tcc_fixed1', 'tcat_general', 'Please quote this purchase order no. for further communications and invoices pertaining to this indent.', true, 0, CURRENT_TIMESTAMP),
  ('tcc_fixed2', 'tcat_general', 'We encourage bulk packaging and avoid plastic. No asbestos to be used in any product or packing material.', true, 1, CURRENT_TIMESTAMP);

-- Dynamic T&C snapshot on the PO.
ALTER TABLE "PurchaseOrder" ADD COLUMN "terms" JSONB;
