module Admin
  class ClubsController < BaseController
    before_action :set_club, only: %i[show grant_comped revoke_comped]

    def index
      @clubs = Club.includes(:teams, subscription: %i[plan admin_comped_by])
                   .order(:name)
    end

    def show
      @subscription = @club.subscription || @club.build_subscription(plan: Plan["free"], status: "active")
      @plans = Plan.ordered.reject { |p| p.slug == "free" }
      @teams = @club.teams.order(:name)
    end

    def grant_comped
      Billing::AdminCompedSubscription.grant(
        club: @club,
        plan_slug: params.require(:plan_slug),
        reason: params[:reason],
        admin: current_admin_account
      )
      redirect_back_or_club notice: "Abbonamento omaggio #{Plan[params[:plan_slug]].name} attivato per #{@club.name}."
    rescue Billing::AdminCompedSubscription::Error, ActiveRecord::RecordInvalid => e
      redirect_back_or_club alert: e.message
    end

    def revoke_comped
      Billing::AdminCompedSubscription.revoke(club: @club, admin: current_admin_account)
      redirect_back_or_club notice: "Abbonamento omaggio revocato per #{@club.name}."
    rescue Billing::AdminCompedSubscription::Error => e
      redirect_back_or_club alert: e.message
    end

    private

    def set_club
      @club = Club.find(params[:id])
    end

    def redirect_back_or_club(notice: nil, alert: nil)
      target = params[:return_to].presence || admin_club_path(@club)
      redirect_to target, notice: notice, alert: alert
    end
  end
end
