import { queryOne } from "../../lib/db.js";

const RAW_PAYLOAD_RETENTION_DAYS = 7;
const RAW_PAYLOAD_PRUNE_BATCH_SIZE = 5_000;
const RAW_PAYLOAD_PRUNE_MAX_BATCHES = 20;

type PruneResult = {
  updated_count: number;
};

export const pruneExpiredPositionRawPayloads = async () => {
  let totalUpdated = 0;

  for (let batch = 0; batch < RAW_PAYLOAD_PRUNE_MAX_BATCHES; batch += 1) {
    const result = await queryOne<PruneResult>(
      `
        with expired as (
          select id
          from positions
          where raw_payload IS NOT NULL
            and server_time < now() - make_interval(days => $1::int)
          order by server_time asc
          limit $2
        ),
        updated as (
          update positions position
          set raw_payload = NULL
          from expired
          where position.id = expired.id
          returning position.id
        )
        select count(*)::int as updated_count
        from updated
      `,
      [RAW_PAYLOAD_RETENTION_DAYS, RAW_PAYLOAD_PRUNE_BATCH_SIZE],
    );

    const updatedCount = result?.updated_count ?? 0;
    totalUpdated += updatedCount;
    if (updatedCount < RAW_PAYLOAD_PRUNE_BATCH_SIZE) {
      break;
    }
  }

  return totalUpdated;
};
