defmodule Mv.Repo.Migrations.AddMembershipFeesTables do
  @moduledoc """
  Updates resources based on their most recent snapshots.

  This file was autogenerated with `mix ash_postgres.generate_migrations`
  """

  use Ecto.Migration

  def up do
    create table(:membership_fee_types, primary_key: false) do
      add :id, :uuid, null: false, default: fragment("uuid_generate_v7()"), primary_key: true
      add :name, :text, null: false
      # Precision: 10 digits total, 2 decimal places (max 99,999,999.99)
      add :amount, :numeric, null: false, precision: 10, scale: 2
      add :interval, :text, null: false
      add :description, :text
    end

    create unique_index(:membership_fee_types, [:name],
             name: "membership_fee_types_unique_name_index"
           )

    # CHECK constraint for interval values (enforced at DB level)
    create constraint(:membership_fee_types, :membership_fee_types_interval_check,
             check: "interval IN ('monthly', 'quarterly', 'half_yearly', 'yearly')"
           )

    # CHECK constraint for non-negative amount
    create constraint(:membership_fee_types, :membership_fee_types_amount_check,
             check: "amount >= 0"
           )

    create table(:membership_fee_cycles, primary_key: false) do
      add :id, :uuid, null: false, default: fragment("uuid_generate_v7()"), primary_key: true
      add :cycle_start, :date, null: false
      # Precision: 10 digits total, 2 decimal places (max 99,999,999.99)
      add :amount, :numeric, null: false, precision: 10, scale: 2
      add :status, :text, null: false, default: "unpaid"
      add :notes, :text

      # CASCADE: Delete cycles when member is deleted
      add :member_id,
          references(:members,
            column: :id,
            name: "membership_fee_cycles_member_id_fkey",
            type: :uuid,
            prefix: "public",
            on_delete: :delete_all
          ),
          null: false

      # RESTRICT: Cannot delete fee type if cycles reference it
      add :membership_fee_type_id,
          references(:membership_fee_types,
            column: :id,
            name: "membership_fee_cycles_membership_fee_type_id_fkey",
            type: :uuid,
            prefix: "public",
            on_delete: :restrict
          ),
          null: false
    end

    # CHECK constraint for status values (enforced at DB level)
    create constraint(:membership_fee_cycles, :membership_fee_cycles_status_check,
             check: "status IN ('unpaid', 'paid', 'suspended')"
           )

    # CHECK constraint for non-negative amount
    create constraint(:membership_fee_cycles, :membership_fee_cycles_amount_check,
             check: "amount >= 0"
           )

    # Indexes as specified in architecture document
    create index(:membership_fee_cycles, [:member_id])
    create index(:membership_fee_cycles, [:membership_fee_type_id])
    create index(:membership_fee_cycles, [:status])
    create index(:membership_fee_cycles, [:cycle_start])

    # Composite unique index: one cycle per member per cycle_start
    create unique_index(:membership_fee_cycles, [:member_id, :cycle_start],
             name: "membership_fee_cycles_unique_cycle_per_member_index"
           )

    # Extend members table with membership fee fields
    alter table(:members) do
      add :membership_fee_start_date, :date

      # RESTRICT: Cannot delete fee type if members are assigned to it
      add :membership_fee_type_id,
          references(:membership_fee_types,
            column: :id,
            name: "members_membership_fee_type_id_fkey",
            type: :uuid,
            prefix: "public",
            on_delete: :restrict
          )
    end

    # Index for efficient lookup of members by fee type
    create index(:members, [:membership_fee_type_id])
  end

  def down do
    # First: Remove members extension (depends on membership_fee_types)
    drop_if_exists index(:members, [:membership_fee_type_id])
    drop constraint(:members, "members_membership_fee_type_id_fkey")

    alter table(:members) do
      remove :membership_fee_type_id
      remove :membership_fee_start_date
    end

    # Second: Drop cycles table (depends on membership_fee_types)
    drop_if_exists unique_index(:membership_fee_cycles, [:member_id, :cycle_start],
                     name: "membership_fee_cycles_unique_cycle_per_member_index"
                   )

    drop_if_exists index(:membership_fee_cycles, [:cycle_start])
    drop_if_exists index(:membership_fee_cycles, [:status])
    drop_if_exists index(:membership_fee_cycles, [:membership_fee_type_id])
    drop_if_exists index(:membership_fee_cycles, [:member_id])

    drop constraint(:membership_fee_cycles, "membership_fee_cycles_member_id_fkey")
    drop constraint(:membership_fee_cycles, "membership_fee_cycles_membership_fee_type_id_fkey")
    drop_if_exists constraint(:membership_fee_cycles, :membership_fee_cycles_status_check)
    drop_if_exists constraint(:membership_fee_cycles, :membership_fee_cycles_amount_check)

    drop table(:membership_fee_cycles)

    # Third: Drop fee types table
    drop_if_exists unique_index(:membership_fee_types, [:name],
                     name: "membership_fee_types_unique_name_index"
                   )

    drop_if_exists constraint(:membership_fee_types, :membership_fee_types_interval_check)
    drop_if_exists constraint(:membership_fee_types, :membership_fee_types_amount_check)

    drop table(:membership_fee_types)
  end
end
