-- AI pipeline tables

CREATE TABLE outlines (
    id              BIGINT          NOT NULL PRIMARY KEY,
    project_id      BIGINT          NOT NULL,
    tenant_id       BIGINT          NOT NULL,
    title           VARCHAR(255)    NOT NULL,
    genre           VARCHAR(64),
    episode_count   INT             NOT NULL DEFAULT 1,
    synopsis        TEXT,
    raw_json        LONGTEXT,
    status          VARCHAR(32)     NOT NULL DEFAULT 'draft',
    created_at      DATETIME(3)     NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    updated_at      DATETIME(3)     NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
    INDEX idx_project (project_id),
    INDEX idx_tenant (tenant_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE episodes (
    id              BIGINT          NOT NULL PRIMARY KEY,
    outline_id      BIGINT          NOT NULL,
    project_id      BIGINT          NOT NULL,
    tenant_id       BIGINT          NOT NULL,
    episode_number  INT             NOT NULL,
    title           VARCHAR(255),
    summary         TEXT,
    script          LONGTEXT,
    status          VARCHAR(32)     NOT NULL DEFAULT 'draft',
    created_at      DATETIME(3)     NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    updated_at      DATETIME(3)     NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
    INDEX idx_outline (outline_id),
    INDEX idx_project (project_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE ai_tasks (
    id              BIGINT          NOT NULL PRIMARY KEY,
    tenant_id       BIGINT          NOT NULL,
    project_id      BIGINT          NOT NULL,
    episode_id      BIGINT,
    task_type       VARCHAR(64)     NOT NULL,
    external_task_id VARCHAR(255),
    status          VARCHAR(32)     NOT NULL DEFAULT 'pending',
    input_image_key VARCHAR(512),
    prompt          TEXT,
    result_video_url VARCHAR(1024),
    error_message   TEXT,
    created_at      DATETIME(3)     NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    updated_at      DATETIME(3)     NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
    INDEX idx_tenant_project (tenant_id, project_id),
    INDEX idx_episode (episode_id),
    INDEX idx_external (external_task_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
