CREATE TABLE forgejo_sync_state (
  key text PRIMARY KEY,
  value jsonb NOT NULL DEFAULT '{}'::jsonb,
  updated_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE webhook_deliveries (
  request_id text PRIMARY KEY,
  delivery_key text NOT NULL,
  event_name text NOT NULL,
  company_id uuid NOT NULL,
  payload jsonb NOT NULL,
  status text NOT NULL,
  received_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE issue_mappings (
  company_id uuid NOT NULL,
  source_id text NOT NULL,
  dedupe_key text NOT NULL,
  title text,
  body text NOT NULL,
  attachment_metadata jsonb NOT NULL DEFAULT '[]'::jsonb,
  manual_review_required boolean NOT NULL DEFAULT false,
  review_reason_code text,
  updated_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (company_id, source_id)
);

CREATE TABLE comment_mappings (
  company_id uuid NOT NULL,
  source_id text NOT NULL,
  dedupe_key text NOT NULL,
  title text,
  body text NOT NULL,
  attachment_metadata jsonb NOT NULL DEFAULT '[]'::jsonb,
  manual_review_required boolean NOT NULL DEFAULT false,
  review_reason_code text,
  updated_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (company_id, source_id)
);

CREATE TABLE review_queue (
  company_id uuid NOT NULL,
  source_kind text NOT NULL,
  source_id text NOT NULL,
  dedupe_key text NOT NULL,
  review_reason_code text NOT NULL,
  review_payload jsonb NOT NULL,
  status text NOT NULL DEFAULT 'pending',
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (company_id, source_kind, source_id)
);

CREATE TABLE reconciliation_runs (
  id bigserial PRIMARY KEY,
  completed_at timestamptz NOT NULL,
  trigger text NOT NULL,
  pending_reviews integer NOT NULL,
  pending_deliveries integer NOT NULL,
  mapped_issues integer NOT NULL,
  mapped_comments integer NOT NULL,
  snapshot jsonb NOT NULL
);
