import { Controller, Get, Param, Query, Res } from '@nestjs/common';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { Response } from 'express';
import { RequirePermissions } from '@/common/auth/decorators';
import { DocumentsService } from './documents.service';
import { buildLocationLabelZpl } from './labels';

@ApiTags('documents')
@ApiBearerAuth()
@Controller('documents')
export class DocumentsController {
  constructor(private readonly docs: DocumentsService) {}

  @Get() @RequirePermissions('reports.read')
  list(@Query('refType') refType: string, @Query('refId') refId: string) { return this.docs.list(refType, refId); }

  @Get(':id/download') @RequirePermissions('reports.read')
  async download(@Param('id') id: string, @Res() res: Response) {
    const d = await this.docs.download(id);
    res.setHeader('Content-Type', d.mimeType);
    res.setHeader('Content-Disposition', `inline; filename="${d.fileName}"`);
    res.send(d.buffer);
  }

  /** ZPL for a pallet/LPN label (RF receive, re-label). */
  @Get('labels/lpn/:lpnNumber') @RequirePermissions('inventory.read')
  lpnLabel(@Param('lpnNumber') lpnNumber: string) { return this.docs.lpnLabelFor(lpnNumber); }

  /** ZPL for a carton label (packing station). */
  @Get('labels/carton/:cartonId') @RequirePermissions('outbound.read')
  cartonLabel(@Param('cartonId') cartonId: string) { return this.docs.cartonLabelFor(cartonId); }

  @Get('labels/location/:code') @RequirePermissions('masterdata.read')
  locationLabel(@Param('code') code: string, @Query('checkDigit') checkDigit?: string) { return { zpl: buildLocationLabelZpl(code, checkDigit) }; }
}
