-- MariaDB baseline schema. The Go startup migrator emits equivalent SQLite SQL.
CREATE TABLE IF NOT EXISTS webhook_events (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  delivery_id VARCHAR(255) NULL UNIQUE,
  event_name VARCHAR(128) NOT NULL,
  repo VARCHAR(255) NOT NULL,
  comment_id BIGINT NULL,
  payload_sha256 VARCHAR(64) NOT NULL,
  created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
  UNIQUE KEY uq_webhook_events_repo_comment (repo, comment_id)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS review_jobs (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  repo VARCHAR(255) NOT NULL,
  pr_number INT NOT NULL,
  head_sha VARCHAR(64) NOT NULL,
  trigger_comment_id BIGINT NOT NULL,
  command VARCHAR(64) NOT NULL,
  command_args TEXT NULL,
  requested_by VARCHAR(255) NOT NULL,
  status VARCHAR(32) NOT NULL,
  last_error TEXT NULL,
  result_json JSON NULL,
  created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
  updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
  started_at DATETIME(6) NULL,
  finished_at DATETIME(6) NULL,
  UNIQUE KEY uq_review_jobs_repo_trigger_comment (repo, trigger_comment_id),
  KEY ix_review_jobs_lookup (repo, pr_number, head_sha, status, created_at)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS review_runs (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  job_id BIGINT NOT NULL,
  status VARCHAR(32) NOT NULL,
  runner_container_id VARCHAR(128) NULL,
  result_json JSON NULL,
  error_message TEXT NULL,
  started_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
  finished_at DATETIME(6) NULL,
  CONSTRAINT fk_review_runs_job FOREIGN KEY (job_id) REFERENCES review_jobs(id) ON DELETE CASCADE,
  KEY ix_review_runs_job_status (job_id, status)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS bot_comments (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  repo VARCHAR(255) NOT NULL,
  pr_number INT NOT NULL,
  head_sha VARCHAR(64) NOT NULL,
  gitea_comment_id BIGINT NOT NULL,
  marker VARCHAR(255) NOT NULL,
  created_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
  updated_at DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
  UNIQUE KEY uq_bot_comments_marker (repo, pr_number, marker),
  KEY ix_bot_comments_repo_pr (repo, pr_number)
) ENGINE=InnoDB;
