class TalentReleasesController < ApplicationController
  include ProjectContext, TalentReleaseContext

  before_action :set_project, only: [:index, :new, :create]
  before_action :set_talent_release, only: [:edit, :update, :destroy]

  include ProjectLayout

  def index
    @talent_releases = filtered_talent_releases.order_by_recent.paginate(page: params[:page])
  end

  def new
    @talent_release = build_talent_release
  end

  def create
    @talent_release = build_talent_release(talent_release_params)

    if @talent_release.save
      log_create_analytics
      AddHeadshotCollectionUidToProjectJob.perform_later(@project)
      SetTagsForReleasableJob.perform_later(@talent_release)
      redirect_to [@project, :talent_releases], notice: t(".notice")
    else
      render :new
    end
  end

  def edit
    @project = @talent_release.project
  end

  def update
    @project = @talent_release.project

    if @talent_release.update(talent_release_params)
      AddHeadshotCollectionUidToProjectJob.perform_later(@project)
      redirect_to [@project, :talent_releases], notice: t(".notice")
    else
      render :edit
    end
  end

  def destroy
    @project = @talent_release.project

    if @talent_release.destroy
      AddHeadshotCollectionUidToProjectJob.perform_later(@project)
      redirect_to [@project, :talent_releases], alert: t(".alert")
    end
  end

  private

  def talent_releases
    if @project
      policy_scope(@project.talent_releases)
    else
      policy_scope(TalentRelease)
    end
  end

  def talent_release_params
    params.require(:talent_release).permit(
      :person_first_name, :person_last_name, :person_phone, :guardian_photo, :person_email,
      :person_address_street1, :person_address_street2, :person_address_city, :person_address_state, :person_address_zip, :person_address_country,
      :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,
      :contract, { photos: [] },
      :applicable_medium_id, :applicable_medium_text, :territory_id, :territory_text, :term_id, :term_text, :restriction_id, :restriction_text
    )
  end

  def build_talent_release(attrs = {})
    authorize @project.talent_releases.build(attrs)
  end

  def filtered_talent_releases
    results = talent_releases

    if params[:query].present?
      results = results.search(params[:query])
    end

    results
  end

  def log_create_analytics
    TrackAnalyticsJob.perform_later(Current.user, Current.account, :track_create_non_native_release, release_type: TalentRelease.to_s, user_agent: request.user_agent, user_ip: request.remote_ip)
  end
end
