module Public
  class ReplayController < SiteBaseController
    layout "marketing_live"

    before_action :set_session_and_recording, only: %i[show stream thumbnail download]
    before_action :authorize_replay_access!, only: %i[show stream thumbnail download]

    def index
      @query = params[:q].to_s.strip
      @recordings = Recording.ready.publicly_listed
                             .includes(stream_session: { match: { team: :club } })
                             .search_replays(@query)
                             .order(recorded_at: :desc, created_at: :desc)
                             .limit(100)
      if params[:club_id].present?
        @recordings = @recordings.joins(:team).where(teams: { club_id: params[:club_id] })
      end
      if params[:team_id].present?
        @recordings = @recordings.where(team_id: params[:team_id])
      end
      @clubs = Club.joins(teams: :recordings)
                   .merge(Recording.ready.publicly_listed)
                   .distinct
                   .order(:name)
      @filter_club = @clubs.find { |c| c.id.to_s == params[:club_id].to_s } if params[:club_id].present?
    end

    def show
      @match = @session.match
    end

    def stream
      Recordings::IncrementViews.new(@recording).call
      serve_video(disposition: "inline")
    end

    def thumbnail
      serve_thumbnail
    end

    def download
      unless download_allowed?
        redirect_to public_replay_path(@session), alert: "Download non disponibile"
        return
      end

      serve_video(disposition: "attachment")
    end

    private

    def serve_video(disposition:)
      Recordings::ServeFromStorage.new(
        key: @recording.storage_key,
        content_type: "video/mp4",
        disposition: disposition,
        filename: disposition == "attachment" ? download_filename : nil
      ).call(self)
    rescue ArgumentError
      head :not_found
    end

    def serve_thumbnail
      key = @recording.thumbnail_storage_key
      return head :not_found if key.blank?

      Recordings::ServeFromStorage.new(
        key: key,
        content_type: "image/jpeg",
        disposition: "inline"
      ).call(self)
    rescue ArgumentError
      head :not_found
    end

    def download_allowed?
      ent = @recording.team.entitlements
      return false unless ent.phone_download_enabled?

      Recordings::AccessPolicy.new(@recording, viewer: current_user).allowed? ||
        Recordings::AccessPolicy.new(@recording, viewer: current_user).manage_allowed?
    end

    def download_filename
      slug = @recording.title_or_default.parameterize.presence || "replay"
      "#{slug}.mp4"
    end

    def set_session_and_recording
      @session = StreamSession.includes(match: { team: :club }).find(params[:id])
      @recording = Recording.not_deleted.find_by(stream_session: @session)
      return if @recording

      redirect_to public_live_path(@session), alert: "Replay non disponibile"
    end

    def authorize_replay_access!
      return if Recordings::AccessPolicy.new(@recording, viewer: current_user).allowed?

      redirect_to public_live_index_path, alert: "Replay non disponibile"
    end
  end
end
