module Admin
  class BillingInvoicesController < BaseController
    before_action :set_club
    before_action :set_invoice, only: %i[edit update]

    def index
      redirect_to admin_billing_path(club_id: @club.id)
    end

    def new
      redirect_to admin_billing_path(club_id: @club.id), alert: "Carica il PDF dalla lista «Pagamenti da fatturare»."
    end

    def create
      @invoice = @club.billing_invoices.build(invoice_params)
      @invoice.source = "manual"
      @invoice.status = "draft"

      if @invoice.save
        redirect_to edit_admin_club_billing_invoice_path(@club, @invoice),
                    notice: "Bozza creata. Carica il PDF dalla pagina Fatturazione o qui sotto."
      else
        @payment = @invoice.billing_payment
        flash.now[:alert] = @invoice.errors.full_messages.join(", ")
        render :new, status: :unprocessable_entity
      end
    end

    def edit
      @payment = @invoice.billing_payment
    end

    def update
      @invoice.assign_attributes(invoice_params.except(:pdf))

      if issuing?
        Billing::IssueInvoice.call(invoice: @invoice, pdf: params.dig(:billing_invoice, :pdf))
        redirect_to admin_billing_path(club_id: @club.id),
                    notice: "Fattura #{@invoice.number} emessa e inviata a #{@club.billing_email}."
      elsif @invoice.save
        redirect_to admin_billing_path(club_id: @club.id), notice: "Fattura #{@invoice.number} aggiornata."
      else
        @payment = @invoice.billing_payment
        flash.now[:alert] = @invoice.errors.full_messages.join(", ")
        render :edit, status: :unprocessable_entity
      end
    rescue Billing::IssueInvoice::Error => e
      @payment = @invoice.billing_payment
      flash.now[:alert] = e.message
      render :edit, status: :unprocessable_entity
    end

    private

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

    def set_invoice
      @invoice = @club.billing_invoices.find(params[:id])
    end

    def issuing?
      params[:commit].to_s == "Emetti e invia via email"
    end

    def invoice_params
      params.require(:billing_invoice).permit(
        :number,
        :issued_on,
        :amount_cents,
        :amount_euros,
        :currency,
        :billing_payment_id,
        :notes,
        :pdf
      ).tap do |p|
        if p[:amount_euros].present?
          p[:amount_cents] = (p.delete(:amount_euros).to_f * 100).round
        end
      end
    end
  end
end
