module Recordings
  class Delete
    def initialize(recording, reason: :manual)
      @recording = recording
      @reason = reason
    end

    def call
      delete_storage_object if @recording.storage_key.present?
      cleanup_local_artifacts

      @recording.update!(
        status: "expired",
        deleted_at: Time.current,
        storage_key: nil,
        thumbnail_storage_key: nil
      )
      @recording
    end

    private

    def delete_storage_object
      storage = Recordings::Storage.new
      storage.delete(key: @recording.storage_key) if @recording.storage_key.present?
      storage.delete(key: @recording.thumbnail_storage_key) if @recording.thumbnail_storage_key.present?
    rescue Recordings::Storage::Error => e
      Rails.logger.warn("[Recordings::Delete] storage delete failed: #{e.message}")
    end

    def cleanup_local_artifacts
      return if @recording.storage_path.blank?

      base = File.join(MatchLiveTv.recordings_local_path, @recording.storage_path)
      FileUtils.rm_rf(base) if Dir.exist?(base)
    end
  end
end
