defmodule Mv.Repo.Migrations.AddNotNullConstraintToUsersRoleId do
  @moduledoc """
  Adds NOT NULL constraint to users.role_id column.

  This ensures that role_id can never be NULL at the database level,
  providing an additional safety layer beyond Ash's allow_nil? false.

  Before running this migration, ensure all existing users have a role_id
  (the previous migration AssignMitgliedRoleToExistingUsers handles this).
  """
  use Ecto.Migration

  def up do
    # First ensure all users have a role_id (safety check)
    # This should already be done by the previous migration, but we check anyway
    execute("""
      UPDATE users
      SET role_id = (
        SELECT id FROM roles WHERE name = 'Mitglied' LIMIT 1
      )
      WHERE role_id IS NULL
    """)

    # Now add NOT NULL constraint
    alter table(:users) do
      modify :role_id, :uuid, null: false
    end
  end

  def down do
    # Remove NOT NULL constraint (allow NULL again)
    alter table(:users) do
      modify :role_id, :uuid, null: true
    end
  end
end
