class Public::MiscReleasesController < Public::BaseController
  before_action :set_account, :set_project, :set_contract_template

  def new
    @misc_release = build_misc_release
  end

  def create
    @misc_release = build_misc_release(misc_release_params_with_locale_and_contract_template)

    if @misc_release.save(context: :native)
      if @misc_release.contract_template.present?
        AttachContractToReleasableJob.perform_later(@misc_release)
      end
    else
      render :new
    end
  end

  private

  def set_project
    @project = @account.projects.find(params[:project_id])
  end

  def set_account
    @account = Account.find_by(slug: params[:account_id])
  end

  def set_contract_template
    @contract_template = @project.contract_templates.find(params[:contract_template_id])
  end

  def misc_releases
    policy_scope(@project.misc_releases)
  end

  def build_misc_release(params = {})
    authorize misc_releases.build(params)
  end

  def misc_release_params
    params
      .require(:misc_release)
      .permit(
        person_params,
        guardian_params,
        questionnaire_params,
        :signature_base64,
        :locale,
        :contract_template,
        :applicable_medium_id,
        :applicable_medium_text,
        :territory_id,
        :territory_text,
        :term_id,
        :term_text,
        :restriction_id,
        :restriction_text,
        photos: [],
      )
  end

  def person_params
    [
      :person_first_name,
      :person_last_name,
      :person_phone,
      :person_email,
      :person_address_street1,
      :person_address_street2,
      :person_address_city,
      :person_address_state,
      :person_address_zip,
      :person_address_country,
    ]
  end

  def guardian_params
    [
      :guardian_first_name,
      :guardian_last_name,
      :guardian_phone,
      :guardian_email,
      :minor,
      :guardian_address_street1,
      :guardian_address_street2,
      :guardian_address_city,
      :guardian_address_state,
      :guardian_address_zip,
      :guardian_address_country,
      :guardian_photo
    ]
  end

  def questionnaire_params
    [
      :question_1_answer,
      :question_2_answer,
      :question_3_answer,
      :question_4_answer,
      :question_5_answer,
      :question_6_answer,
      :question_7_answer,
      :question_8_answer,
      :question_9_answer,
      :question_10_answer,
      :question_11_answer,
      :question_12_answer,
      :question_13_answer,
      :question_14_answer,
      :question_15_answer,
    ]
  end

  def misc_release_params_with_locale
    misc_release_params.merge(locale: I18n.locale)
  end

  def misc_release_params_with_locale_and_contract_template
    misc_release_params_with_locale.merge(contract_template: @contract_template)
  end
end
