# frozen_string_literal: true

class Api::Mobile::UrlRedirectsController < Api::Mobile::BaseController
  before_action :fetch_url_redirect_by_external_id, only: :url_redirect_attributes
  before_action :fetch_url_redirect_by_token, only: %i[stream hls_playlist download]
  before_action :mark_rental_as_viewed, only: :hls_playlist
  before_action :check_for_expired_rentals, only: %i[stream hls_playlist]
  after_action :increment_product_uses_count, only: %i[stream download]
  after_action -> { create_consumption_event!(ConsumptionEvent::EVENT_TYPE_WATCH) }, only: [:stream, :hls_playlist]
  after_action -> { create_consumption_event!(ConsumptionEvent::EVENT_TYPE_DOWNLOAD) }, only: [:download]
  before_action :fetch_product_file, only: %i[stream hls_playlist download]

  def url_redirect_attributes
    # By default the purchase is valid, this is because the url redirect could be generated by an admin
    # and therefore would not have an associated purchase object
    purchase_valid = @url_redirect.purchase ? @url_redirect.purchase.successful_and_valid? : true
    render json: { success: true, product: @url_redirect.product_json_data, purchase_valid: }
  end

  def fetch_placeholder_products
    render json: { success: true, placeholder_products: [] }
  end

  def stream
    m3u8_playlist_link = api_mobile_hls_playlist_url(@url_redirect.token,
                                                     @product_file.external_id,
                                                     mobile_token: Api::Mobile::BaseController::MOBILE_TOKEN,
                                                     host: UrlService.api_domain_with_protocol)
    render json: {
      success: true,
      playlist_url: @product_file.hls_playlist.nil? ? @url_redirect.signed_video_url(@product_file) : m3u8_playlist_link,
      subtitles: @product_file.subtitle_files_for_mobile
    }
  end

  def hls_playlist
    hls_playlist_data = @product_file.hls_playlist
    e404 if hls_playlist_data.blank?
    render plain: hls_playlist_data, content_type: "application/x-mpegurl"
  end

  def download
    redirect_to @url_redirect.signed_location_for_file(@product_file), allow_other_host: true
  end

  private
    def fetch_product_file
      @product_file = if @url_redirect.installment.present?
        @url_redirect.installment.product_files.find_by_external_id(permitted_params[:product_file_id])
      else
        @url_redirect.product_file(permitted_params[:product_file_id])
      end
      e404 if @product_file.nil?
    end

    def mark_rental_as_viewed
      @url_redirect.mark_rental_as_viewed!
    end

    def check_for_expired_rentals
      return if !@url_redirect.is_rental || !@url_redirect.rental_expired?

      render json: { success: false, message: "Your rental has expired." }, status: :unauthorized
    end

    def create_consumption_event!(event_type)
      ConsumptionEvent.create_event!(
        event_type:,
        platform: ConsumptionEvent.determine_platform(request.user_agent),
        url_redirect_id: @url_redirect.id,
        product_file_id: @product_file&.id,
        purchase_id: @url_redirect.purchase_id,
        product_id: @url_redirect.purchase&.link_id || @url_redirect.link_id,
        ip_address: request.remote_ip,
      )
    end

    def permitted_params
      params.permit(:product_file_id)
    end

    def increment_product_uses_count
      return if @url_redirect.nil?

      @url_redirect.increment!(:uses, 1)
      @url_redirect.mark_as_seen
    end
end
