module Api
  module V1
    class RecordingsController < BaseController
      before_action :set_recording

      def update
        authorize_manage!
        @recording.update!(recording_update_attrs)
        render json: recording_json(@recording)
      end

      def destroy
        authorize_manage!
        Recordings::Delete.new(@recording).call
        head :no_content
      end

      def download
        url = Recordings::DownloadUrl.new(@recording, viewer: current_user).call
        render json: { download_url: url, expires_in_seconds: MatchLiveTv.replay_download_url_ttl_seconds }
      rescue Recordings::DownloadUrl::NotAllowed
        render json: { error: "Download non disponibile per il tuo piano", error_code: "download_not_allowed" },
               status: :forbidden
      rescue ArgumentError => e
        render json: { error: e.message }, status: :unprocessable_entity
      end

      def publish_youtube
        authorize_manage!
        ent = @recording.team.entitlements
        unless ent.premium_full? && ent.youtube_enabled?
          return render json: { error: "Republicazione YouTube con Premium Full" }, status: :forbidden
        end

        Recordings::PublishToYoutubeJob.perform_async(@recording.id)
        render json: { queued: true, message: "Pubblicazione su YouTube in corso" }
      end

      private

      def set_recording
        team_ids = current_user.manageable_teams.map(&:id)
        @recording = Recording.not_deleted
                              .includes(stream_session: :match)
                              .where(team_id: team_ids)
                              .find(params[:id])
      end

      def authorize_manage!
        team = @recording.team
        return if team.club.owned_by?(current_user)
        return if current_user.manageable_teams.exists?(id: team.id)

        render json: { error: "Non autorizzato" }, status: :forbidden
      end

      def recording_update_attrs
        p = params.require(:recording).permit(:privacy_status, :title)
        p = p.to_h
        p[:privacy_status] = "unlisted" if p[:privacy_status] == "private"
        if params.dig(:recording, :metadata).present?
          p[:metadata] = @recording.metadata.merge(
            params[:recording][:metadata].to_unsafe_h.stringify_keys
          )
        end
        p
      end

      def recording_json(recording)
        session = recording.stream_session
        match = session.match
        ent = recording.team.entitlements
        {
          id: recording.id,
          session_id: session.id,
          match_id: match.id,
          title: recording.title_or_default,
          opponent_name: match.opponent_name,
          team_name: match.team.name,
          team_id: recording.team_id,
          status: recording.status,
          status_label: recording.status_label,
          privacy_status: recording.privacy_status,
          ended_at: session.ended_at,
          recorded_at: recording.recorded_at_or_fallback,
          duration_secs: recording.duration_secs,
          duration_label: recording.duration_label,
          byte_size: recording.byte_size,
          byte_size_label: recording.byte_size_label,
          view_count: recording.view_count,
          views_label: recording.views_label,
          replay_url: recording.replay_url,
          playback_url: recording.playback_stream_url,
          thumbnail_url: recording.thumbnail_url,
          download_enabled: ent.phone_download_enabled?,
          youtube_video_id: recording.youtube_video_id,
          youtube_watch_url: recording.youtube_watch_url,
          youtube_publish_enabled: ent.premium_full? && ent.youtube_enabled?,
          expires_at: recording.expires_at,
          metadata: recording.metadata
        }
      end
    end
  end
end
