defmodule Towerops.Repo.Migrations.CreateLoginAttempts do
  use Ecto.Migration

  def change do
    create table(:login_attempts, primary_key: false) do
      add :id, :binary_id, primary_key: true

      # User association (nullable for GDPR anonymization)
      add :user_id, references(:users, type: :binary_id, on_delete: :nilify_all)

      # Login metadata
      add :email, :string
      add :success, :boolean, null: false
      add :method, :string, null: false
      add :failure_reason, :string

      # Network/location data (preserved for security analysis)
      add :ip_address, :string, null: false
      add :user_agent, :text
      add :country_code, :string
      add :country_name, :string
      add :city_name, :string
      add :subdivision_1_name, :string

      # GDPR tracking
      add :anonymized_at, :utc_datetime

      timestamps(type: :utc_datetime, updated_at: false)
    end

    create index(:login_attempts, [:user_id])
    create index(:login_attempts, [:email])
    create index(:login_attempts, [:ip_address])
    create index(:login_attempts, [:inserted_at])
    create index(:login_attempts, [:success])
    create index(:login_attempts, [:anonymized_at])
    create index(:login_attempts, [:user_id, :inserted_at])
  end
end
