defmodule Towerops.Preseem.SyncLog do
  @moduledoc """
  Audit log for Preseem sync operations.
  """
  use Ecto.Schema

  import Ecto.Changeset

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

  @valid_statuses ~w(success partial failed)

  schema "preseem_sync_logs" do
    field :status, :string
    field :records_synced, :integer, default: 0
    field :errors, :map
    field :duration_ms, :integer
    field :inserted_at, :utc_datetime

    belongs_to :organization, Towerops.Organizations.Organization
    belongs_to :integration, Towerops.Integrations.Integration
  end

  def changeset(sync_log, attrs) do
    sync_log
    |> cast(attrs, [
      :organization_id,
      :integration_id,
      :status,
      :records_synced,
      :errors,
      :duration_ms,
      :inserted_at
    ])
    |> validate_required([:organization_id, :integration_id, :status, :inserted_at])
    |> validate_inclusion(:status, @valid_statuses)
    |> foreign_key_constraint(:organization_id)
    |> foreign_key_constraint(:integration_id)
  end
end
