-- Web Designer task queue — design requests the agent drains one at a time.
--
-- The admin submits a brief (target page, prompt, draft, assets) which lands
-- here as `queued`. The console runner claims the oldest queued row, runs the
-- design agent, builds, and auto-publishes (git commit), then marks it
-- `published` (or `failed`). The queue is FIFO by (sort_order, task_id).
--
-- `assets` is JSON: { "images": [{ "url": "/media/x.webp", "alt": "" }],
--                     "videos": ["https://instagram.com/reel/..."] }
-- `result` is JSON, written on completion: { commit, summary, live, error }.

CREATE TABLE IF NOT EXISTS `cja_tasks` (
  `task_id`      int(10) unsigned NOT NULL AUTO_INCREMENT,

  `title`        varchar(200)  NOT NULL DEFAULT '',
  -- "/about", "/services", or "new:<slug>" to create a brand-new page
  `target_page`  varchar(200)  NOT NULL DEFAULT '',

  `prompt`       text          DEFAULT NULL,   -- the request / special instructions
  `draft`        mediumtext    DEFAULT NULL,   -- optional draft content
  `assets`       longtext      DEFAULT NULL CHECK (json_valid(`assets`)),

  `status`       enum('queued','running','published','failed','canceled')
                               NOT NULL DEFAULT 'queued',
  `result`       longtext      DEFAULT NULL CHECK (`result` IS NULL OR json_valid(`result`)),

  `sort_order`   int(11)       NOT NULL DEFAULT 0,

  `created_at`   datetime      NOT NULL DEFAULT current_timestamp(),
  `started_at`   datetime      DEFAULT NULL,
  `finished_at`  datetime      DEFAULT NULL,

  PRIMARY KEY (`task_id`),
  KEY `idx_cja_tasks_queue` (`status`, `sort_order`, `task_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
