CREATE TABLE "ledger_reconciliation_repairs" (
	"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
	"user_id" uuid NOT NULL,
	"expected_balance_agorot" bigint NOT NULL,
	"actual_balance_agorot" bigint NOT NULL,
	"balance_delta_agorot" bigint NOT NULL,
	"expected_lifetime_agorot" bigint NOT NULL,
	"actual_lifetime_agorot" bigint NOT NULL,
	"repaired_columns" text NOT NULL,
	"recurrence" boolean DEFAULT false NOT NULL,
	"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "tax_documents" (
	"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
	"purchase_id" uuid NOT NULL,
	"side" text NOT NULL,
	"provider_tax_doc_id" text NOT NULL,
	"idempotency_key" text NOT NULL,
	"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "cron_cursors" (
	"job_key" text PRIMARY KEY NOT NULL,
	"last_processed_at" timestamp with time zone NOT NULL,
	"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "outbox" ADD COLUMN "dead_at" timestamp with time zone;
--> statement-breakpoint
CREATE INDEX "ledger_recon_repairs_user_idx" ON "ledger_reconciliation_repairs" USING btree ("user_id");
--> statement-breakpoint
CREATE INDEX "ledger_recon_repairs_created_idx" ON "ledger_reconciliation_repairs" USING btree ("created_at");
--> statement-breakpoint
CREATE UNIQUE INDEX "tax_documents_purchase_side_uq" ON "tax_documents" USING btree ("purchase_id","side");
--> statement-breakpoint
CREATE INDEX "outbox_dead_at_idx" ON "outbox" USING btree ("dead_at");
--> statement-breakpoint
-- H2 backfill: mark already-exhausted rows terminal so they surface in outbox_abandoned
-- and become re-drivable. Cap literal (3) matches OUTBOX_MAX_RETRIES at migration time.
UPDATE "outbox"
SET "dead_at" = COALESCE("failed_at", "created_at", now())
WHERE "processed_at" IS NULL AND "dead_at" IS NULL AND "retry_count" >= 3;
