import { query } from '../config/database.js';

export class ProcessingBatch {
  static async create(batchData) {
    const {
      id,
      userId,
      name,
      totalFiles,
      totalOriginalSize,
      optimizationSettings
    } = batchData;

    const sql = `
      INSERT INTO processing_batches (
        id, user_id, name, total_files, total_original_size, optimization_settings
      ) VALUES (?, ?, ?, ?, ?, ?)
    `;

    await query(sql, [
      id, userId, name, totalFiles, totalOriginalSize, 
      JSON.stringify(optimizationSettings)
    ]);

    return this.findById(id);
  }

  static async findById(id) {
    const sql = 'SELECT * FROM processing_batches WHERE id = ?';
    const results = await query(sql, [id]);
    const batch = results[0] || null;
    
    if (batch && batch.optimization_settings) {
      batch.optimization_settings = JSON.parse(batch.optimization_settings);
    }
    
    return batch;
  }

  static async findByUserId(userId, limit = 20) {
    const sql = `
      SELECT * FROM processing_batches 
      WHERE user_id = ? 
      ORDER BY created_at DESC 
      LIMIT ?
    `;
    const results = await query(sql, [userId, limit]);
    
    return results.map(batch => ({
      ...batch,
      optimization_settings: batch.optimization_settings ? 
        JSON.parse(batch.optimization_settings) : null
    }));
  }

  static async updateProgress(id, completedFiles, failedFiles) {
    const sql = `
      UPDATE processing_batches 
      SET completed_files = ?, failed_files = ?
      WHERE id = ?
    `;
    await query(sql, [completedFiles, failedFiles, id]);
  }

  static async updateStatus(id, status, downloadUrl = null) {
    let sql = 'UPDATE processing_batches SET status = ?';
    const params = [status];

    if (status === 'completed') {
      sql += ', completed_at = NOW()';
      
      if (downloadUrl) {
        sql += ', download_url = ?, download_expires_at = DATE_ADD(NOW(), INTERVAL 7 DAY)';
        params.push(downloadUrl);
      }
    }

    sql += ' WHERE id = ?';
    params.push(id);

    await query(sql, params);
  }

  static async updateOptimizedSize(id, totalOptimizedSize) {
    const sql = `
      UPDATE processing_batches 
      SET total_optimized_size = ?
      WHERE id = ?
    `;
    await query(sql, [totalOptimizedSize, id]);
  }

  static async cleanupExpiredDownloads() {
    const sql = `
      UPDATE processing_batches 
      SET download_url = NULL, download_expires_at = NULL
      WHERE download_expires_at < NOW()
    `;
    await query(sql);
  }

  static async getBatchWithJobs(id) {
    const batch = await this.findById(id);
    if (!batch) return null;

    const jobsSql = `
      SELECT * FROM processing_jobs 
      WHERE batch_id = ? 
      ORDER BY created_at
    `;
    const jobs = await query(jobsSql, [id]);

    return {
      ...batch,
      jobs
    };
  }
}