# frozen_string_literal: true

class Api::BroadcastsController < Api::ApiController
  deserializable_resource :broadcast, only: [:update]

  include ProjectContext

  before_action :set_project
  before_action :set_broadcast, only: [:show, :update]

  def index
    render jsonapi: broadcasts, class: { Broadcast: SerializableBroadcast }
  end

  def show
    render jsonapi:
      @broadcast,
      class: {
        Broadcast: SerializableBroadcast,
        "ActiveStorage::Attachment".to_sym => ActiveStorage::SerializableAttachment
      },
      include: [:files]
  end

  def update
    file_params.each do |file|
      if file.is_a?(String)
        @broadcast.files.attach(file)
      else
        file[:io] = StringIO.new(Base64.decode64(file[:io]))
        @broadcast.files.attach(file.to_h.symbolize_keys)
      end
    end
    @broadcast.save!

    render jsonapi:
      @broadcast,
      class: {
        Broadcast: SerializableBroadcast,
        "ActiveStorage::Attachment".to_sym => ActiveStorage::SerializableAttachment
      },
      include: [:files]
  end

  private

  def file_params
    broadcast_params = params.require(:broadcast).permit!
    broadcast_params[:files]
  end

  def broadcasts
    policy_scope(@project.broadcasts.where(status: %w[created idle]))
  end

  def set_broadcast
    @broadcast = authorize policy_scope(@project.broadcasts).find(params[:id])
  end
end
