defmodule Towerops.Workers.LoginHistoryCleanupWorker do
  @moduledoc """
  Oban worker for cleaning up old login attempt records.

  Data retention policy:
  - Active records: 365 days (1 year)
  - Anonymized records: 90 days after anonymization

  This worker runs daily at 2 AM via Oban cron.
  """
  use Oban.Worker, queue: :maintenance

  import Ecto.Query

  alias Towerops.Accounts.LoginAttempt
  alias Towerops.Repo

  @impl Oban.Worker
  @spec perform(Oban.Job.t()) :: {:ok, %{deleted: non_neg_integer(), anonymized_deleted: non_neg_integer()}}
  def perform(_job) do
    # Delete login attempts older than retention period (365 days)
    retention_days = Application.get_env(:towerops, :login_history_retention_days, 365)
    cutoff = DateTime.add(DateTime.utc_now(), -retention_days, :day)

    {count, _} =
      LoginAttempt
      |> where([la], la.inserted_at < ^cutoff)
      |> where([la], is_nil(la.anonymized_at))
      |> Repo.delete_all()

    # Delete anonymized records older than 90 days
    anon_cutoff = DateTime.add(DateTime.utc_now(), -90, :day)

    {anon_count, _} =
      LoginAttempt
      |> where([la], not is_nil(la.anonymized_at))
      |> where([la], la.anonymized_at < ^anon_cutoff)
      |> Repo.delete_all()

    {:ok, %{deleted: count, anonymized_deleted: anon_count}}
  end
end
