-- Migration: add procurement contract storage for RFQs
-- Generated on 2025-09-29

CREATE TABLE IF NOT EXISTS rfq_contracts (
  contract_id        uuid PRIMARY KEY DEFAULT uuid_generate_v7(),
  rfq_id             uuid NOT NULL REFERENCES rfq_headers(rfq_id) ON DELETE CASCADE,
  vendor_id          uuid NOT NULL REFERENCES vendors(vendor_id) ON DELETE RESTRICT,
  vendor_name        text NOT NULL,
  contract_number    text NOT NULL,
  title              text NOT NULL,
  status             text NOT NULL DEFAULT 'draft',
  currency           text NULL,
  total_value        numeric(18,2) DEFAULT 0,
  effective_date     date DEFAULT NULL,
  expiry_date        date DEFAULT NULL,
  contract_payload   jsonb NOT NULL,
  created_by         uuid DEFAULT NULL,
  created_at         timestamptz NOT NULL DEFAULT now(),
  updatedAt          timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_rfq_contracts_rfq ON rfq_contracts(rfq_id);
CREATE INDEX IF NOT EXISTS idx_rfq_contracts_vendor ON rfq_contracts(vendor_id);
CREATE INDEX IF NOT EXISTS idx_rfq_contracts_number ON rfq_contracts(contract_number);

-- Seed Procurement Contract Detail modal for existing tenants
INSERT INTO modules (module_id, name, config, org_id, branch_id, icon, aria_label, description)
SELECT
  '0194a8b2-1035-7123-8123-123456789abc'::uuid,
  'Procurement Contract Detail',
  $json$
  {
    "title": "Procurement Contract Detail",
    "body": [
      { "type":"detail-view", "tableName":"rfq_contracts", "filterField":"contract_id",
        "columnLabels": {
          "contract_number": "Contract #",
          "vendor_name": "Vendor",
          "status": "Status",
          "total_value": "Total Value",
          "currency": "Currency",
          "effective_date": "Effective",
          "expiry_date": "Expiry",
          "created_at": "Created",
          "updatedAt": "Updated"
        }
      },
  { "type":"html","id":"aiDraftActions","html":"<div class='flex justify-between items-center my-2'><div class='font-semibold'>AI Draft</div><div><button class='btn btn-sm btn-primary' onclick='generateContractAiDraft()'>Generate with AI</button> <button class='btn btn-sm btn-ghost' onclick='viewContractAiDraft()'>View Draft</button></div></div>" },
  { "type":"html","id":"pdfActions","html":"<div class='flex justify-between items-center my-2'><div class='font-semibold'>Contract PDF</div><div><button class='btn btn-sm btn-secondary' onclick='generateContractPdf()'>Generate PDF</button> <button class='btn btn-sm' onclick='downloadContractPdf()'>Download PDF</button></div></div>" },
  { "type":"html","html":"<div class='divider my-2'>Summary</div>" },
  { "type":"html","id":"contractSummaryContainer","html":"<div id='contractSummary' class='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3'></div>" },
  { "type":"html","html":"<div class='divider my-2'>Line Items</div>" },
  { "type":"html","id":"contractLineItems","html":"<div class='overflow-x-auto'><table class='table table-zebra w-full text-sm'><thead><tr><th>Description</th><th class='text-right'>Qty</th><th>UoM</th><th class='text-right'>Unit Price</th><th class='text-right'>Line Total</th></tr></thead><tbody id='contractLineItemsBody'><tr class='opacity-70'><td colspan='5'>No line items captured yet.</td></tr></tbody></table></div>" }
    ],
    "footer":[{"type":"button","label":"Close","onClick":"closeModal"}]
  }
  $json$::jsonb,
  NULL, NULL, 'fa-file-contract', 'Procurement Contract Detail', 'View of generated RFQ contract payload'
WHERE NOT EXISTS (
  SELECT 1 FROM modules WHERE module_id = '0194a8b2-1035-7123-8123-123456789abc'::uuid
);

-- Ensure existing records pick up the latest modal definition
UPDATE modules
SET config = $json$
  {
    "title": "Procurement Contract Detail",
    "body": [
      { "type":"detail-view", "tableName":"rfq_contracts", "filterField":"contract_id",
        "columnLabels": {
          "contract_number": "Contract #",
          "vendor_name": "Vendor",
          "status": "Status",
          "total_value": "Total Value",
          "currency": "Currency",
          "effective_date": "Effective",
          "expiry_date": "Expiry",
          "created_at": "Created",
          "updatedAt": "Updated"
        }
      },
  { "type":"html","id":"aiDraftActions","html":"<div class='flex justify-between items-center my-2'><div class='font-semibold'>AI Draft</div><div><button class='btn btn-sm btn-primary' onclick='generateContractAiDraft()'>Generate with AI</button> <button class='btn btn-sm btn-ghost' onclick='viewContractAiDraft()'>View Draft</button></div></div>" },
  { "type":"html","id":"pdfActions","html":"<div class='flex justify-between items-center my-2'><div class='font-semibold'>Contract PDF</div><div><button class='btn btn-sm btn-secondary' onclick='generateContractPdf()'>Generate PDF</button> <button class='btn btn-sm' onclick='downloadContractPdf()'>Download PDF</button></div></div>" },
  { "type":"html","html":"<div class='divider my-2'>Summary</div>" },
  { "type":"html","id":"contractSummaryContainer","html":"<div id='contractSummary' class='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3'></div>" },
  { "type":"html","html":"<div class='divider my-2'>Line Items</div>" },
  { "type":"html","id":"contractLineItems","html":"<div class='overflow-x-auto'><table class='table table-zebra w-full text-sm'><thead><tr><th>Description</th><th class='text-right'>Qty</th><th>UoM</th><th class='text-right'>Unit Price</th><th class='text-right'>Line Total</th></tr></thead><tbody id='contractLineItemsBody'><tr class='opacity-70'><td colspan='5'>No line items captured yet.</td></tr></tbody></table></div>" }
    ],
    "footer":[{"type":"button","label":"Close","onClick":"closeModal"}]
  }
$json$::jsonb
WHERE module_id = '0194a8b2-1035-7123-8123-123456789abc'::uuid;

-- Ensure the new modal is visible within the Dev program experience
INSERT INTO program_modules (program_id, module_id, config_json)
SELECT
  '0194a8b2-def0-7123-8123-123456789abc'::uuid,
  '0194a8b2-1035-7123-8123-123456789abc'::uuid,
  NULL
WHERE NOT EXISTS (
  SELECT 1 FROM program_modules
  WHERE program_id = '0194a8b2-def0-7123-8123-123456789abc'::uuid
    AND module_id = '0194a8b2-1035-7123-8123-123456789abc'::uuid
);
