import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Documento } from './entities/documento.entity';
import * as fs from 'fs';
import * as path from 'path';

const UPLOAD_DIR = process.env.UPLOAD_DIR || '/opt/hefesto/uploads';

@Injectable()
export class DocumentosService {
  constructor(@InjectRepository(Documento) private repo: Repository<Documento>) {
    // Ensure upload dir exists
    if (!fs.existsSync(UPLOAD_DIR)) {
      fs.mkdirSync(UPLOAD_DIR, { recursive: true });
    }
  }

  findByDemanda(demandaId: string) {
    return this.repo.find({ where: { demanda_id: demandaId }, order: { created_at: 'DESC' } });
  }

  async findOne(id: string) {
    const doc = await this.repo.findOne({ where: { id } });
    if (!doc) throw new NotFoundException('Documento não encontrado');
    return doc;
  }

  async upload(demandaId: string, file: Express.Multer.File, tipo?: string) {
    const ext = path.extname(file.originalname);
    const filename = `${demandaId}_${Date.now()}${ext}`;
    const destPath = path.join(UPLOAD_DIR, filename);

    fs.writeFileSync(destPath, file.buffer);

    return this.repo.save({
      demanda_id: demandaId,
      nome_arquivo: file.originalname,
      tipo: tipo || 'outro',
      caminho: filename,
      tamanho: file.size,
    });
  }

  async remove(id: string) {
    const doc = await this.findOne(id);
    const filePath = path.join(UPLOAD_DIR, doc.caminho);
    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath);
    }
    await this.repo.delete(id);
    return { deleted: true };
  }

  getFilePath(doc: Documento) {
    return path.join(UPLOAD_DIR, doc.caminho);
  }
}
