-- Add account_sequence column to reward_ledger_entries
ALTER TABLE "reward_ledger_entries" ADD COLUMN "account_sequence" VARCHAR(20);

-- Add indexes for account_sequence on reward_ledger_entries
CREATE INDEX "idx_account_status" ON "reward_ledger_entries"("account_sequence", "reward_status");
CREATE INDEX "idx_account_created" ON "reward_ledger_entries"("account_sequence", "created_at" DESC);

-- Add account_sequence column to reward_summaries
ALTER TABLE "reward_summaries" ADD COLUMN "account_sequence" VARCHAR(20);

-- Add unique constraint and index for account_sequence on reward_summaries
CREATE UNIQUE INDEX "reward_summaries_account_sequence_key" ON "reward_summaries"("account_sequence");
CREATE INDEX "idx_summary_account" ON "reward_summaries"("account_sequence");

-- Add account_sequence column to settlement_records
ALTER TABLE "settlement_records" ADD COLUMN "account_sequence" VARCHAR(20);

-- Add index for account_sequence on settlement_records
CREATE INDEX "idx_settlement_account" ON "settlement_records"("account_sequence");

-- Backfill: set account_sequence = user_id for existing records
UPDATE "reward_ledger_entries" SET "account_sequence" = "user_id" WHERE "account_sequence" IS NULL;
UPDATE "reward_summaries" SET "account_sequence" = "user_id" WHERE "account_sequence" IS NULL;
UPDATE "settlement_records" SET "account_sequence" = "user_id" WHERE "account_sequence" IS NULL;

-- Make account_sequence NOT NULL after backfill
ALTER TABLE "reward_ledger_entries" ALTER COLUMN "account_sequence" SET NOT NULL;
ALTER TABLE "reward_summaries" ALTER COLUMN "account_sequence" SET NOT NULL;
ALTER TABLE "settlement_records" ALTER COLUMN "account_sequence" SET NOT NULL;
