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

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

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

      # Link to users_tokens for authentication
      add :user_token_id, references(:users_tokens, type: :binary_id, on_delete: :delete_all),
        null: false

      # Device/browser metadata (from User-Agent parsing)
      add :device_name, :string
      add :browser_name, :string
      add :browser_version, :string
      add :os_name, :string
      add :os_version, :string
      add :device_type, :string

      # Network/location data
      add :ip_address, :string, null: false
      add :country_code, :string
      add :country_name, :string
      add :city_name, :string
      add :subdivision_1_name, :string

      # Activity tracking
      add :last_activity_at, :utc_datetime, null: false
      add :expires_at, :utc_datetime, null: false

      # GDPR tracking
      add :anonymized_at, :utc_datetime

      timestamps(type: :utc_datetime)
    end

    create index(:browser_sessions, [:user_id])
    create unique_index(:browser_sessions, [:user_token_id])
    create index(:browser_sessions, [:expires_at])
    create index(:browser_sessions, [:last_activity_at])
    create index(:browser_sessions, [:anonymized_at])
  end
end
