#
# Errors Controller
#
# @author [alameen]
#
class IssuesController < ApplicationController
  protect_from_forgery with: :null_session, only: [:track]

  skip_before_action :authenticate_user!, only: [:track]

  before_action :set_project, only: [:index, :show, :destroy]
  before_action :set_issue, only: [:show, :destroy]
  before_action :set_project_from_token, only: [:track]
  before_action :authorize_user, only: [:index, :show, :destroy]

  protect_from_forgery except: [:track]

  def index
    @issues = @project.issues.includes(:occurances).page(params[:page]).per(10)
  end

  def track
    @issue = Issue.track(@project, payload_params)
    msg = @issue.save ? t('issue.created') : @issue.errors.full_messages.first

    render json: {
      success: @issue.errors.blank?,
      message: msg,
      issue_id: @issue.try(:id)
    }
  end

  def show
    @payload = @issue.try(:parsed_payload)
  end

  def destroy
    @issue.destroy
    render json: { success: true, issue: { id: @issue.id }}
  end

  private

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

  def set_issue
    @issue = @project.issues.where('issues.id = ?', params[:id]).take
  end

  def payload_params
    params[:payload] || params[:exception]
  end

  def set_project_from_token
    @project = Project.find_by(authentication_token: params[:token])
    if @project.blank?
      render json: { success: false, message: t('project.invalid_token') }
    end
  end

  def authorize_user
    return if @project.user?(current_user)

    redirect_to new_project_request_path(@project)
  end
end
