// 🆕 Audit Report Approvals controller — base `audit-report-approvals`
//    so the PermissionGuard maps it to the audit-report-approvals module.
import {
  Controller, Get, Post, Param, Body, Query, Req, Res, ParseIntPipe,
} from '@nestjs/common';
import type { Response } from 'express';
import { AuditReportApprovalsService } from './audit-report-approvals.service';

@Controller('audit-report-approvals')
export class AuditReportApprovalsController {
  constructor(private readonly service: AuditReportApprovalsService) {}

  // GET /api/audit-report-approvals/queue?page=&search=&approved=&auditorId=&auditType=&status=&year=&month=&from=&to=
  @Get('queue')
  async queue(
    @Req() req: any,
    @Query('page', new ParseIntPipe({ optional: true })) page = 1,
    @Query('limit', new ParseIntPipe({ optional: true })) limit = 10,
    @Query('search') search?: string,
    @Query('approved') approved?: 'all' | 'approved' | 'pending',
    @Query('auditorId') auditorId?: string,
    @Query('auditType') auditType?: string,
    @Query('status') status?: string,
    @Query('year') year?: string,
    @Query('month') month?: string,
    @Query('from') from?: string,
    @Query('to') to?: string,
  ) {
    return this.service.queue(req.user?.id, {
      page, limit, search, approved: approved ?? 'all',
      auditorId, auditType, status, year, month, from, to,
    });
  }

  @Post(':id/approve')
  async approve(@Param('id', ParseIntPipe) id: number, @Req() req: any) {
    return this.service.approve(id, req.user?.id);
  }

  @Post(':id/reject')
  async reject(
    @Param('id', ParseIntPipe) id: number,
    @Body() body: { reason?: string },
    @Req() req: any,
  ) {
    return this.service.reject(id, req.user?.id, body?.reason);
  }

  // 🆕 Stream a report/doc scoped by SCHEME (bypasses the auditor-assignment
  //    check used by /audits/:id/documents). Gated by the audit-report-approvals
  //    module permission, so a QRS manager can open any QRS audit's files.
  // GET /api/audit-report-approvals/:id/file/:docType
  @Get(':id/file/:docType')
  async openFile(
    @Param('id', ParseIntPipe) id: number,
    @Param('docType') docType: string,
    @Req() req: any,
    @Res() res: Response,
  ) {
    const { stream, size, mimeType, filename } =
      await this.service.openReportFile(id, docType, req.user?.id);
    res.setHeader('Content-Type', mimeType);
    res.setHeader('Content-Length', size);
    res.setHeader(
      'Content-Disposition',
      `inline; filename="${encodeURIComponent(filename)}"`,
    );
    stream.pipe(res);
  }
}