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

  def change do
    # Mobile sessions - long-lived tokens for mobile app authentication
    create table(:mobile_sessions, primary_key: false) do
      add :id, :binary_id, primary_key: true
      add :user_id, references(:users, type: :binary_id, on_delete: :delete_all), null: false
      add :token, :string, null: false
      add :device_name, :string
      add :device_os, :string
      add :app_version, :string
      add :last_used_at, :utc_datetime, null: false
      add :expires_at, :utc_datetime, null: false

      timestamps(type: :utc_datetime)
    end

    create index(:mobile_sessions, [:user_id])
    create unique_index(:mobile_sessions, [:token])
    create index(:mobile_sessions, [:expires_at])

    # QR login tokens - temporary tokens for QR code authentication
    create table(:qr_login_tokens, primary_key: false) do
      add :id, :binary_id, primary_key: true
      add :user_id, references(:users, type: :binary_id, on_delete: :delete_all), null: false
      add :token, :string, null: false
      add :expires_at, :utc_datetime, null: false
      add :completed_at, :utc_datetime

      add :mobile_session_id,
          references(:mobile_sessions, type: :binary_id, on_delete: :nilify_all)

      timestamps(type: :utc_datetime)
    end

    create unique_index(:qr_login_tokens, [:token])
    create index(:qr_login_tokens, [:user_id])
    create index(:qr_login_tokens, [:expires_at])
  end
end
