-- =============================================================================
-- B03 대용량 파일 청크 업로드 세션 테이블
-- DBMS: MariaDB 10.6+
-- =============================================================================

USE aislo_db;

CREATE TABLE IF NOT EXISTS upload_sessions (
  id VARCHAR(36) PRIMARY KEY,
  project_id CHAR(36) NOT NULL,
  original_filename VARCHAR(255) NOT NULL,
  file_size_bytes BIGINT NOT NULL,
  chunk_size_bytes INT NOT NULL,
  total_chunks INT NOT NULL,
  completed_chunks INT NOT NULL DEFAULT 0,
  status ENUM('in_progress', 'completed', 'failed') NOT NULL DEFAULT 'in_progress',
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  INDEX idx_upload_sessions_project_id (project_id),
  INDEX idx_upload_sessions_status (status),
  CONSTRAINT fk_upload_sessions_project_id
    FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS upload_chunks (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  session_id VARCHAR(36) NOT NULL,
  chunk_index INT NOT NULL,
  chunk_hash VARCHAR(64) NOT NULL,
  size_bytes INT NOT NULL,
  stored_at VARCHAR(500) NOT NULL,
  completed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uq_upload_chunks_session_index (session_id, chunk_index),
  INDEX idx_upload_chunks_session_id (session_id),
  CONSTRAINT fk_upload_chunks_session_id
    FOREIGN KEY (session_id) REFERENCES upload_sessions(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
