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

  def up do
    # Add use_sites boolean field (default false)
    alter table(:organizations) do
      add :use_sites, :boolean, default: false, null: false
    end

    # Backfill: Orgs with 2+ sites OR 1 named site (not "Default") → use_sites = true
    # This detects existing multi-site setups
    execute """
    UPDATE organizations
    SET use_sites = true
    WHERE id IN (
      SELECT organization_id
      FROM sites
      GROUP BY organization_id
      HAVING COUNT(*) > 1 OR (COUNT(*) = 1 AND MAX(name) != 'Default')
    )
    """
  end

  def down do
    alter table(:organizations) do
      remove :use_sites
    end
  end
end
