// Cleanup tracker for tests that create server-side state.
//
// The integration tier creates real resources (statuses, follows, …) against
// real instances. A test that posts a status MUST register a cleanup hook,
// or the bot account grows a tail of "halflight integration test 17499..."
// posts over time. The tracker collects best-effort deletions so a single
// `afterAll` call drains the lot without each test reinventing the
// boilerplate.
//
// Best-effort: failures (404 from a follow-up server-side TTL, network
// hiccup, missing endpoint) are swallowed. The test still passes if the
// cleanup didn't land — the next bootstrap-test-rig run can wipe the bot
// inbox by hand.

import type { ApiContext } from 'src/lib/api-context'

type CleanupFn = () => Promise<void>

export class RigCleanupTracker {
  private tasks: CleanupFn[] = []

  /** Track a status for deletion. */
  trackStatus(api: ApiContext, statusId: string): void {
    this.tasks.push(async () => {
      await api.delete(`/api/v1/statuses/${statusId}`)
    })
  }

  /** Track an unfollow against an account id. */
  trackFollow(api: ApiContext, accountId: string): void {
    this.tasks.push(async () => {
      await api.post(`/api/v1/accounts/${accountId}/unfollow`)
    })
  }

  /** Register an arbitrary cleanup task. */
  track(fn: CleanupFn): void {
    this.tasks.push(fn)
  }

  /** Drain every registered task. Errors are caught and logged but never
   *  re-thrown — cleanup that 404s is a normal outcome on flaky networks
   *  and we'd rather the test report green than have the user re-run the
   *  bootstrap script. */
  async drain(): Promise<void> {
    const tasks = this.tasks.splice(0, this.tasks.length)
    for (const task of tasks) {
      try {
        await task()
      } catch (e) {
        // eslint-disable-next-line no-console
        console.warn(`[RigCleanupTracker] task failed: ${(e as Error).message}`)
      }
    }
  }
}
