CREATE TABLE IF NOT EXISTS launch_audits (
    tenant_key TEXT NOT NULL,
    audit_id TEXT NOT NULL,
    target_url TEXT NOT NULL,
    ok BOOLEAN NOT NULL DEFAULT FALSE,
    report JSONB NOT NULL DEFAULT '{}'::jsonb,
    payload JSONB NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    PRIMARY KEY (tenant_key, audit_id)
);

CREATE INDEX IF NOT EXISTS launch_audits_tenant_updated_idx
    ON launch_audits (tenant_key, updated_at DESC);

CREATE TABLE IF NOT EXISTS launch_receipts (
    tenant_key TEXT NOT NULL,
    audit_id TEXT NOT NULL,
    receipt_id TEXT NOT NULL,
    payload JSONB NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    PRIMARY KEY (tenant_key, receipt_id),
    FOREIGN KEY (tenant_key, audit_id)
      REFERENCES launch_audits (tenant_key, audit_id)
      ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS launch_receipts_audit_idx
    ON launch_receipts (tenant_key, audit_id, created_at DESC);
