import { Injectable } from '@nestjs/common';
import * as path from 'path';
import * as fs from 'fs';

@Injectable()
export class UploadService {
  
  async processUpload(lokasi: string, tempFilePath: string) {
    const baseDir = path.resolve(process.cwd(), '..', 'api'); 
    const targetFolder = path.join(baseDir, lokasi);
    const targetFile = path.join(targetFolder, 'att2000.mdb');

    if (!fs.existsSync(targetFolder)) {
      fs.mkdirSync(targetFolder, { recursive: true });
    }

    if (fs.existsSync(targetFile)) {
      const dateStr = new Date().toISOString().replace(/T/, '_').replace(/:/g, '').split('.')[0];
      const backupFile = `${targetFile}.bak_${dateStr}`;
      
      // Copy old file to backup
      fs.copyFileSync(targetFile, backupFile);

      // Rotate backups (keep max 3)
      const files = fs.readdirSync(targetFolder);
      const backups = files
        .filter(f => f.startsWith('att2000.mdb.bak_'))
        .sort()
        .reverse(); // Newest first

      if (backups.length > 3) {
        // Delete older backups
        for (let i = 3; i < backups.length; i++) {
          fs.unlinkSync(path.join(targetFolder, backups[i]));
        }
      }
    }

    // Move uploaded file
    fs.copyFileSync(tempFilePath, targetFile);
    fs.unlinkSync(tempFilePath); // Remove temp file

    return {
      status: 'success',
      message: `File MDB berhasil di-replace/diunggah untuk lokasi ${lokasi}`,
      path: `${lokasi}/att2000.mdb`
    };
  }
}
