module Recordings
  class FinalizeSession
    def initialize(session)
      @session = session
    end

    def call
      team = @session.match.team
      return unless team.entitlements.can_access_recordings?

      retention_days = team.entitlements.recording_retention_days
      expires_at = retention_days.positive? ? retention_days.days.from_now : nil

      recording = Recording.find_or_initialize_by(stream_session: @session)
      recording.assign_attributes(
        team: team,
        status: "processing",
        title: default_title,
        privacy_status: privacy_from_session,
        storage_path: @session.mediamtx_path_name,
        recorded_at: @session.ended_at || Time.current,
        expires_at: expires_at,
        error_message: nil,
        metadata: initial_metadata(team)
      )
      recording.save!
      recording
    end

    private

    def default_title
      match = @session.match
      "#{match.team.name} vs #{match.opponent_name}"
    end

    def privacy_from_session
      @session.privacy_status == "public" ? "public" : "unlisted"
    end

    def initial_metadata(team)
      ent = team.entitlements
      {
        "source_platform" => @session.platform,
        "session_privacy" => @session.privacy_status,
        "auto_publish_youtube" => ent.premium_full? && ent.youtube_enabled? && @session.platform == "youtube",
        "ai" => {}
      }
    end
  end
end
