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

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

      add :organization_id, references(:organizations, type: :binary_id, on_delete: :delete_all),
        null: false

      add :device_id, references(:devices, type: :binary_id, on_delete: :delete_all)

      add :name, :string, null: false
      add :check_type, :string, null: false
      add :description, :text

      # Generic check settings (following Icinga2's Checkable pattern)
      add :interval_seconds, :integer, null: false, default: 60
      add :retry_interval_seconds, :integer, null: false, default: 30
      add :max_check_attempts, :integer, null: false, default: 3
      add :timeout_ms, :integer, null: false, default: 5000
      add :enabled, :boolean, null: false, default: true

      # Check-specific configuration (JSONB, like Icinga2's vars)
      add :config, :map, null: false, default: %{}

      # State tracking
      add :current_state, :integer, null: false, default: 3
      add :current_state_type, :string, null: false, default: "soft"
      add :current_check_attempt, :integer, null: false, default: 1
      add :last_check_at, :utc_datetime
      add :last_state_change_at, :utc_datetime
      add :last_hard_state_change_at, :utc_datetime

      # Flapping detection
      add :enable_flapping, :boolean, null: false, default: false
      add :flapping_threshold_low, :float, null: false, default: 25.0
      add :flapping_threshold_high, :float, null: false, default: 30.0
      add :is_flapping, :boolean, null: false, default: false
      add :flapping_state_changes, :integer, null: false, default: 0
      add :flapping_window_start_at, :utc_datetime

      # Passive checks
      add :enable_passive_checks, :boolean, null: false, default: false
      add :freshness_threshold_seconds, :integer
      add :check_key, :string

      # Agent assignment (which agent executes this check)
      add :agent_token_id, references(:agent_tokens, type: :binary_id, on_delete: :nilify_all)

      timestamps(type: :utc_datetime)
    end

    create index(:checks, [:organization_id])
    create index(:checks, [:device_id])
    create index(:checks, [:check_type])
    create index(:checks, [:enabled])
    create index(:checks, [:agent_token_id])
    create unique_index(:checks, [:check_key], where: "check_key IS NOT NULL")
  end
end
