class TaskRequestsController < ApplicationController
  layout "project"

  before_action :set_project
  before_action :build_task_request, only: [:new, :create]
  before_action :set_task_request, only: [:show, :edit, :update, :cancel]

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

  def new
  end

  def create
    @task_request.attributes = task_request_params_with_email

    if @task_request.save
      log_create_analytics
      taskme_url = url_for([:admin, @task_request])
      SubmitHubspotTaskRequestFormJob.perform_later(@task_request.user_email, taskme_url)
    else
      render :new
    end
  end

  def show
    @files = @task_request.files.paginate(page: params[:page])
  end
  
  def edit
  end

  def update
    if @task_request.update(task_request_params)
      redirect_to [@project, :task_requests], notice: t(".notice")
    else
      render :edit
    end
  end

  def cancel
    @task_request.cancelled!
    redirect_to [@project, :task_requests], notice: t(".notice")
  end

  private

  def task_request_params
    params.require(:task_request).permit(:description, :deadline, :time_allowed, :additional_notes, files: [])
  end

  def task_request_params_with_email
    task_request_params.merge(user_email: Current.user.email)
  end

  def set_project
    @project = policy_scope(Project).find(params[:project_id])
  end

  def set_task_request
    @task_request = authorize policy_scope(TaskRequest).find(params[:id])
  end

  def task_requests
    authorize policy_scope(@project.task_requests)
  end

  def build_task_request
    @task_request = authorize @project.task_requests.build
  end

  def log_create_analytics
    TrackAnalyticsJob.perform_later(Current.user, Current.account, :track_create_task_request, user_agent: request.user_agent, user_ip: request.remote_ip)
  end
end
