-- AI file builder.
-- AI-built deliverable files (drafts until approved into product_files).
CREATE TABLE IF NOT EXISTS deliverable_builds (
  id               INT AUTO_INCREMENT PRIMARY KEY,
  product_id       INT NOT NULL,
  website_id       INT NOT NULL,
  deliverable_key  VARCHAR(20)  NOT NULL,              -- brief deliverable id, e.g. D1
  deliverable_name VARCHAR(255) NOT NULL,
  mode             ENUM('direct','batch') NOT NULL DEFAULT 'direct',
  status           ENUM('queued','running','batch_pending','paused','collect','ready','needs_attention','failed','approved','rejected') NOT NULL DEFAULT 'queued',
  feedback         TEXT,                               -- your revision notes (regenerations)
  parent_build_id  INT NULL,
  batch_id         INT NULL,
  container_id     VARCHAR(120) NULL,                  -- Anthropic code-execution container (reused for revisions)
  messages         LONGTEXT,                           -- conversation so far (pause_turn continuation)
  iterations       INT NOT NULL DEFAULT 0,
  files            JSON,                               -- downloaded files [{name, stored, size, mime, pages, kind}]
  report           JSON,                               -- the AI's build report (self-checks, seller to-dos)
  checks           JSON,                               -- automatic server-side checks
  review           JSON,                               -- AI review of the finished PDF(s)
  usage_json       JSON,
  error            TEXT,
  started_at       DATETIME,
  finished_at      DATETIME,
  approved_at      DATETIME,
  created_at       DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at       DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  KEY idx_product (product_id, deliverable_key),
  KEY idx_status (status),
  CONSTRAINT fk_build_product FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE
) ENGINE=InnoDB CHARSET=utf8mb4;

ALTER TABLE batches
  MODIFY type ENUM('research_market','generate_guide','generate_content','generate_brief','build_deliverable') NOT NULL;
