class ProjectMembershipsController < ApplicationController
  include ProjectContext

  layout "project"

  before_action :set_project, except: :destroy
  before_action :set_project_membership, only: [:destroy]

  def index
    @account_managers = @project.account.managers.order(:email)
    @project_memberships = project_memberships.order_by_user_role_and_user_email(Current.account)
    @project_membership = project_memberships.build
  end

  def create
    @project_membership = build_project_membership(project_membership_params)

    if @project_membership.save_and_update_account_membership
      flash.notice = t(".notice")
      UserMailer.project_invitation(@project_membership.user, @project, user_is_new: @project_membership.new_user?).deliver_later
    else
      flash.alert = alert_for(@project_membership)
    end

    redirect_to [@project, :project_memberships]
  end

  def destroy
    @project_membership.destroy
    redirect_to [@project_membership.project, :project_memberships], alert: t(".alert")
  end

  private

  def set_project_membership
    @project_membership = authorize project_memberships.find(params[:id])
  end

  def project_memberships
    if @project
      policy_scope(@project.project_memberships)
    else
      policy_scope(ProjectMembership) 
    end
  end

  def build_project_membership(params = {})
    authorize project_memberships.build(params)
  end

  def project_membership_params
    params.require(:project_membership).permit(:user_email)
  end

  def user_email_param
    project_membership_params.fetch(:user_email)
  end

  def alert_for(project_membership)
    if project_membership.errors.any?
      project_membership.errors.full_messages.first
    else
      t(".alert")
    end
  end
end
