defmodule Towerops.Accounts.LoginAttemptTest do
  use Towerops.DataCase

  import Towerops.AccountsFixtures

  alias Towerops.Accounts.LoginAttempt

  describe "changeset/2" do
    test "valid changeset for successful login" do
      changeset =
        LoginAttempt.changeset(%LoginAttempt{}, %{
          success: true,
          method: "password",
          ip_address: "192.168.1.1",
          email: "user@example.com"
        })

      assert changeset.valid?
    end

    test "valid changeset for failed login with failure_reason" do
      changeset =
        LoginAttempt.changeset(%LoginAttempt{}, %{
          success: false,
          method: "password",
          ip_address: "192.168.1.1",
          failure_reason: "invalid_credentials"
        })

      assert changeset.valid?
    end

    test "error when success is true but failure_reason is present" do
      changeset =
        LoginAttempt.changeset(%LoginAttempt{}, %{
          success: true,
          method: "password",
          ip_address: "192.168.1.1",
          failure_reason: "invalid_credentials"
        })

      refute changeset.valid?
      assert "must be nil when login is successful" in errors_on(changeset).failure_reason
    end

    test "error when success is false but failure_reason is missing" do
      changeset =
        LoginAttempt.changeset(%LoginAttempt{}, %{
          success: false,
          method: "password",
          ip_address: "192.168.1.1"
        })

      refute changeset.valid?
      assert "is required when login fails" in errors_on(changeset).failure_reason
    end
  end

  describe "anonymize_changeset/1" do
    test "sets user_id to nil and records anonymized_at timestamp" do
      user = user_fixture()

      login_attempt =
        Towerops.Repo.insert!(%LoginAttempt{
          user_id: user.id,
          email: "user@example.com",
          success: true,
          method: "password",
          ip_address: "192.168.1.1"
        })

      changeset = LoginAttempt.anonymize_changeset(login_attempt)

      assert changeset.changes.user_id == nil
      assert %DateTime{} = changeset.changes.anonymized_at
    end
  end
end
