import { Controller, Get, Post, Patch, Delete, Body, Param, Res, UploadedFile, UseInterceptors, Query } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import type { Response } from 'express';
import { OrdensServicoService } from './ordens-servico.service';

@Controller('ordens-servico')
export class OrdensServicoController {
  constructor(private svc: OrdensServicoService) {}

  @Get() findAll() { return this.svc.findAll(); }
  @Get(':id') findOne(@Param('id') id: string) { return this.svc.findOne(id); }
  @Post() create(@Body() body: any) { return this.svc.create(body); }
  @Patch(':id') update(@Param('id') id: string, @Body() body: any) { return this.svc.update(id, body); }
  @Delete(':id') remove(@Param('id') id: string) { return this.svc.remove(id); }

  @Get('by-demanda/:demandaId') findByDemanda(@Param('demandaId') demandaId: string) { return this.svc.findByDemanda(demandaId); }

  @Post(':id/iniciar') iniciar(@Param('id') id: string) { return this.svc.iniciar(id); }
  @Post(':id/concluir') concluir(@Param('id') id: string) { return this.svc.concluir(id); }
  @Post(':id/cancelar') cancelar(@Param('id') id: string) { return this.svc.cancelar(id); }
  @Post(':id/status') updateStatus(@Param('id') id: string, @Body('status') status: string) { return this.svc.updateStatus(id, status); }

  @Post(':id/avaliacao') avaliacao(@Param('id') id: string, @Body() body: any) {
    return this.svc.createAvaliacao({ ...body, ordem_servico_id: id });
  }

  // Document versioning
  @Get(':id/documentos') findDocumentos(@Param('id') id: string) { return this.svc.findDocumentos(id); }

  @Post(':id/documentos')
  @UseInterceptors(FileInterceptor('file', { limits: { fileSize: 50 * 1024 * 1024 } }))
  uploadDocumento(
    @Param('id') id: string,
    @UploadedFile() file: Express.Multer.File,
    @Body('fornecedor_id') fornecedorId?: string,
  ) {
    return this.svc.uploadDocumento(id, file, fornecedorId);
  }

  @Get('documentos/:docId/download')
  async downloadDocumento(@Param('docId') docId: string, @Res() res: Response) {
    const { doc, filePath } = await this.svc.downloadDocumento(docId);
    res.download(filePath, doc.nome_arquivo);
  }

  // Check fornecedor OS
  @Get('check-fornecedor/:fornecedorId') 
  async checkFornecedor(@Param('fornecedorId') fornecedorId: string) {
    const hasOS = await this.svc.fornecedorHasOS(fornecedorId);
    return { hasOS };
  }
}
