module Public
  class ClubRecordingsController < WebBaseController
    before_action :require_login!
    before_action :set_club
    before_action -> { require_club_owner!(@club) }
    before_action :set_recording, only: %i[update destroy publish_youtube]

    def index
      @stats = Recordings::ClubStats.new(@club).call
      @recordings = Recording.for_club(@club)
                             .not_deleted
                             .includes(stream_session: { match: :team })
                             .order(recorded_at: :desc, created_at: :desc)
      @teams = @club.teams.order(:name)
    end

    def update
      privacy = params.require(:recording).permit(:privacy_status, :title)[:privacy_status]
      attrs = {}
      attrs[:privacy_status] = privacy if privacy.in?(Recording::PRIVACY_STATUSES)
      title = params.dig(:recording, :title)
      attrs[:title] = title if title.present?
      @recording.update!(attrs)
      redirect_to public_club_recordings_path(@club), notice: "Replay aggiornato"
    rescue ActiveRecord::RecordInvalid => e
      redirect_to public_club_recordings_path(@club), alert: e.record.errors.full_messages.join(", ")
    end

    def destroy
      Recordings::Delete.new(@recording).call
      redirect_to public_club_recordings_path(@club), notice: "Replay eliminato"
    end

    def publish_youtube
      ent = @recording.team.entitlements
      unless ent.premium_full? && ent.youtube_enabled?
        redirect_to public_club_recordings_path(@club), alert: "Republicazione YouTube con Premium Full"
        return
      end

      Recordings::PublishToYoutubeJob.perform_async(@recording.id)
      redirect_to public_club_recordings_path(@club), notice: "Pubblicazione su YouTube avviata"
    end

    private

    def set_club
      @club = current_user.owned_clubs.find(params[:club_id])
    end

    def set_recording
      @recording = Recording.for_club(@club).not_deleted.find(params[:id])
    end
  end
end
