import { Injectable } from '@nestjs/common';
import { promises as fs } from 'fs';
import * as path from 'path';
import { v4 as uuid } from 'uuid';
import { mkdir, rename } from 'fs/promises'
import { dirname } from 'path'

@Injectable()
export class StorageService {

  async saveTemp(file: Express.Multer.File): Promise<string> {
    const filename = `${uuid()}-${file.originalname}`;
    const dest = path.join('./uploads/temp', filename);
    await fs.mkdir('./uploads/temp', { recursive: true });
    await fs.writeFile(dest, file.buffer);
    return `/uploads/temp/${filename}`;  // ✅ fix: was /temp/${filename}
  }

  async promoteToPermament(tempUrl: string, destination: string): Promise<string> {
    const filename = path.basename(tempUrl)

    const src = path.join(process.cwd(), 'uploads', 'temp', filename)
    const destDir = path.join(process.cwd(), 'uploads', destination)
    const destPath = path.join(destDir, filename)

    await mkdir(destDir, { recursive: true })

    try {
      await fs.access(src)   // check file exists
    } catch {
      throw new Error(`Temp file missing: ${src}`)
    }

    await rename(src, destPath)

    return `/uploads/${destination}/${filename}`
  }

  async deleteFile(url: string): Promise<void> {
    // url is like /uploads/customers/filename.jpg
    // strip leading slash and resolve from project root
    const filepath = path.join('.', url);
    await fs.unlink(filepath).catch(() => { }); // silent fail if already gone
  }
}