-- Replace offers_book_winners_idx with covering version that includes all ORDER BY
-- columns for the Book.ts winners CTE. Enables sort-free DISTINCT ON by providing
-- index entries in (group_cols, expr_tick, block_number, obligation_units, hash) order
-- after seeking on (obligation_id, buy).
DROP INDEX "router_v1.14"."offers_book_winners_idx";--> statement-breakpoint

CREATE INDEX "offers_book_winners_covering_idx" ON "router_v1.14"."offers" (
  "obligation_id",
  "buy",
  "group_chain_id",
  "group_maker",
  "group_group",
  (CASE WHEN "buy" THEN -"tick" ELSE "tick" END),
  "block_number",
  "obligation_units" DESC,
  "hash"
);--> statement-breakpoint

-- Extend offers_group_winner_expr_idx with obligation_units DESC to cover the full
-- ORDER BY of the group_winners CTE in OfferFormulas.ts. Without this column the
-- planner must sort after the index scan.
DROP INDEX "router_v1.14"."offers_group_winner_expr_idx";--> statement-breakpoint

CREATE INDEX "offers_group_winner_expr_idx" ON "router_v1.14"."offers" (
  "group_chain_id",
  "group_maker",
  "group_group",
  "obligation_id",
  "buy",
  (CASE WHEN "buy" THEN -"tick" ELSE "tick" END),
  "block_number",
  "obligation_units" DESC,
  "hash"
);
