defmodule Towerops.Preseem.FleetProfile do
  @moduledoc """
  Fleet-wide model performance profiles. Groups devices by manufacturer+model
  to identify patterns, capacity ceilings, and firmware correlations.
  """
  use Ecto.Schema

  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id

  schema "preseem_fleet_profiles" do
    field :manufacturer, :string
    field :model, :string
    field :firmware_version, :string
    field :device_count, :integer
    field :avg_subscribers, :float
    field :avg_qoe_score, :float
    field :avg_capacity_score, :float
    field :capacity_ceiling, :integer
    field :avg_busy_hours, :float
    field :performance_data, :map
    field :computed_at, :utc_datetime

    belongs_to :organization, Towerops.Organizations.Organization
  end

  def changeset(profile, attrs) do
    profile
    |> cast(attrs, [
      :organization_id,
      :manufacturer,
      :model,
      :firmware_version,
      :device_count,
      :avg_subscribers,
      :avg_qoe_score,
      :avg_capacity_score,
      :capacity_ceiling,
      :avg_busy_hours,
      :performance_data,
      :computed_at
    ])
    |> validate_required([:organization_id, :manufacturer, :model, :device_count, :computed_at])
    |> unique_constraint([:organization_id, :manufacturer, :model, :firmware_version],
      name: :preseem_fleet_profiles_org_model_fw_idx
    )
    |> foreign_key_constraint(:organization_id)
  end
end
