class Admin::Accounting::Students::Billing::TransactionsController < Admin::Accounting::Controller
  include Admin::Accounting::Students::BillingScoped

  before_action :prevent_template_update, only: :update

  def index
    render_success :ok, json: transactions.map { |t| transaction_props(t) }
  end

  def create
    plan_transactions.build_detail(detail_params) if params[:charge]
    plan_transactions.build_detail(detail_params(:credit)) if params[:credit]

    if bill_plan.save
      render_success :ok
    else
      render_error :unprocessable_entity, errors: bill_plan
    end
  end

  def update
    if transaction.update(memo: params[:memo])
      render_success :ok
    else
      render_error :unprocessable_entity, errors: transaction
    end
  end

  def destroy
    if plan_transaction.destroy
      render_success :ok
    else
      render_error :unprocessable_entity, errors: transaction
    end
  end

  private
    def transactions
      student.billing_transaction_details
        .includes(
          :subcategory,
          :days,
          :template_transaction,
          plan_transactions: { plan: :student }
        )
        .by_plan_school_year(params[:school_year_id])
    end

    def plan_transactions
      bill_plan.plan_transactions.build
    end

    def transaction
      @transaction ||= transactions.find_by(id: params[:id])
    end

    def plan_transaction
      @plan_transaction ||= student.billing_plan_transactions.find_by(detail: transaction)
    end

    def subcategory(type)
      current_school.accounting_subcategories.find_by(id: params[type][:subcategory_id])
    end

    def set_amount(type)
      return params[type][:amount] if type == :charge || params[type][:fixed]

      params[:charge][:amount].to_f * params[:credit][:amount].to_f / 100
    end

    def prevent_template_update
      return unless transaction.template_transaction

      render_error :unprocessable_entity, message: 'Cannot update template line item.'
    end

    def detail_params(type=:charge)
      params[type].permit(:memo).merge(
        subcategory: subcategory(type),
        amount: set_amount(type),
        charge: type == :charge,
        transaction_days: params[:days]
      )
    end

    def transaction_props(transaction)
      {
        id: transaction.id,
        student_id: student.id,
        subcategory_id: transaction.subcategory_id,
        subcategory_name: transaction.subcategory.decorate.title,
        memo: transaction.memo,
        amount: transaction.amount.to_f,
        installments: transaction.days.count,
        total: transaction.amount.to_f * transaction.days.count,
        charge: transaction.charge,
        type: transaction.type?,
        template: transaction.decorate.template_name
      }
    end
end
