class Admin::Communication::BatchEmailsController < Admin::Communication::Controller
  def index
    render_success :ok, json: emails.by_status(params[:status]).map { |email| props(email) }
  end

  def show
    render_success :ok, json: props(email)
  end

  def create
    email = emails.build(email_params)
    email.author = current_employee
    email.employees = employees
    email.contacts = contacts
    email.students = students
    if email.save
      render_success :created, json: props(email)
    else
      render_error :unprocessable_entity, errors: email
    end
  end

  def update
    email.employees = employees
    email.contacts = contacts
    email.students = students
    if email.update(email_params)
      render_success :ok, json: props(email)
    else
      render_error :unprocessable_entity, errors: email
    end
  end

  def destroy
    if email.destroy
      render_success :ok
    else
      render_error :unprocessable_entity, errors: email
    end
  end

  def send_email
    email.send_email
    render_success :ok, json: props(email)
  end

  def recipients
    render_success :ok, json: email_recipients.map { |r| recipient_props(r) }
  end

  private
    def emails
      current_school.communication_batch_emails.includes(:employees, :students, :contacts)
    end

    def email
      @email ||= emails.find_by(id: params[:id])
    end

    def email_params
      params.permit(:subject, :description, :editor_type, :html, :design)
    end

    def employees
      current_school.employees.joins(:primary_email_address).where(id: params[:employee_ids])
    end

    def contacts
      current_school.contacts.joins(:primary_email_address).where(id: params[:contact_ids])
    end

    def students
      current_school.students.joins(:primary_email_address).where(id: params[:student_ids])
    end

    def email_recipients
      email.recipients.includes(:associated)
    end

    def recipient_props(recipient)
      {
        id: recipient.id,
        associated_id: recipient.associated_id,
        type: recipient.associated_type,
        name: recipient.associated.full_name(:reverse),
        email: recipient.associated.primary_email_address.address,
        events: recipient.events.map { |e| event_props(e) }
      }
    end

    def event_props(event)
      {
        id: event.id,
        event: event.event,
        timestamp: event.created_at
      }
    end

    def props(email)
      {
        id: email.id,
        subject: email.subject,
        description: email.description,
        editor_type: email.editor_type,
        html: email.html,
        design: email.design,
        created_at: email.created_at,
        status: email.status,
        employee_ids: email.employee_ids,
        student_ids: email.student_ids,
        contact_ids: email.contact_ids
      }
    end
end
