-- ============================================================================
-- EasyStream Upload Progress System Installation
-- ============================================================================
-- This SQL file adds upload progress tracking to EasyStream
--
-- Features:
-- - Real-time upload progress tracking
-- - Processing status updates
-- - Multiple upload queue management
-- - Error handling and reporting
--
-- Installation:
-- docker exec -i easystream-db mysql -u easystream -peasystream easystream < __install/add_upload_progress_system.sql
-- ============================================================================

CREATE TABLE IF NOT EXISTS `db_upload_progress` (
  `db_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `upload_id` varchar(64) NOT NULL COMMENT 'Unique upload identifier',
  `usr_id` int(10) unsigned NOT NULL COMMENT 'User ID',
  `filename` varchar(255) NOT NULL COMMENT 'Original filename',
  `file_type` varchar(20) NOT NULL COMMENT 'video, audio, image, document, etc.',
  `file_size` bigint(20) unsigned NOT NULL DEFAULT 0 COMMENT 'Total file size in bytes',
  `uploaded_bytes` bigint(20) unsigned NOT NULL DEFAULT 0 COMMENT 'Bytes uploaded so far',
  `upload_percent` decimal(5,2) NOT NULL DEFAULT 0.00 COMMENT 'Upload percentage (0-100)',
  `status` varchar(20) NOT NULL DEFAULT 'uploading' COMMENT 'uploading, processing, encoding, completed, failed, cancelled',
  `processing_step` varchar(100) DEFAULT NULL COMMENT 'Current processing step description',
  `error_message` text DEFAULT NULL COMMENT 'Error message if failed',
  `file_key` varchar(32) DEFAULT NULL COMMENT 'File key after successful upload',
  `started_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `completed_at` datetime DEFAULT NULL,
  PRIMARY KEY (`db_id`),
  UNIQUE KEY `idx_upload_id` (`upload_id`),
  KEY `idx_usr_status` (`usr_id`, `status`),
  KEY `idx_started_at` (`started_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Upload progress tracking';

-- Cleanup old completed uploads (older than 7 days)
CREATE EVENT IF NOT EXISTS cleanup_upload_progress
ON SCHEDULE EVERY 1 DAY
DO
  DELETE FROM `db_upload_progress`
  WHERE `status` IN ('completed', 'failed', 'cancelled')
  AND `completed_at` < DATE_SUB(NOW(), INTERVAL 7 DAY);

-- ============================================================================
-- END OF INSTALLATION
-- ============================================================================
