import { Body, Controller, Delete, Get, Param, Post, Query, Res, UploadedFile, UseGuards, UseInterceptors } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import type { Response } from 'express';
import { CurrentTenant } from '../../common/auth/current-tenant.decorator';
import { CurrentUser } from '../../common/auth/current-user.decorator';
import { JwtAuthGuard } from '../../common/auth/jwt-auth.guard';
import { RequireTenantGuard } from '../../common/auth/require-tenant.guard';
import { PermissionsGuard } from '../../common/auth/permissions.guard';
import { RequirePermission } from '../../common/auth/permissions.decorator';
import { type CrmActor } from '../../common/crm/crm-record.helper';
import { RequestTenantContext } from '../../common/tenancy/tenant-query.helper';
import { ListFilesQuery } from './dto/list-files.query';
import { FilesService, MAX_FILE_SIZE, UploadedMulterFile } from './files.service';

const INLINE_SAFE_TYPES = new Set(['application/pdf', 'image/png', 'image/jpeg', 'image/gif', 'image/webp', 'text/plain']);

/** Sends stored bytes so a browser can never run them as a page: only safe types open inline, everything else downloads. */
function sendStoredFile(res: Response, file: { metadata: { mimeType: string; fileName: string; sizeBytes: number }; bytes: Uint8Array }, inline: boolean) {
  const showInline = inline && INLINE_SAFE_TYPES.has(file.metadata.mimeType.toLowerCase());
  res.setHeader('Content-Type', file.metadata.mimeType);
  res.setHeader('Content-Disposition', `${showInline ? 'inline' : 'attachment'}; filename="${encodeURIComponent(file.metadata.fileName)}"`);
  res.setHeader('Content-Length', file.metadata.sizeBytes);
  res.setHeader('X-Content-Type-Options', 'nosniff');
  res.setHeader('Content-Security-Policy', "default-src 'none'; sandbox");
  res.send(file.bytes);
}

@Controller('files')
@UseGuards(JwtAuthGuard, RequireTenantGuard, PermissionsGuard)
@RequirePermission('files', 'read')
export class FilesController {
  constructor(private readonly files: FilesService) {}

  // Returns list of uploaded tenant files. GET /api/files
  @Get()
  list(@CurrentTenant() t: RequestTenantContext, @Query() q: ListFilesQuery) {
    return this.files.list(t, q);
  }

  // Returns metadata for a single file. GET /api/files/:id
  @Get(':id')
  get(@CurrentTenant() t: RequestTenantContext, @Param('id') id: string) {
    return this.files.getMetadata(t, id);
  }

  // Downloads raw binary file attachment from database. GET /api/files/:id/download
  @Get(':id/download')
  async download(@CurrentTenant() t: RequestTenantContext, @Param('id') id: string, @Res() res: Response) {
    sendStoredFile(res, await this.files.download(t, id), false);
  }

  // Streams a safe file type inline for browser preview; other types download. GET /api/files/:id/view
  @Get(':id/view')
  async view(@CurrentTenant() t: RequestTenantContext, @Param('id') id: string, @Res() res: Response) {
    sendStoredFile(res, await this.files.download(t, id), true);
  }

  // Uploads and stores file in MySQL LONGBLOB with record link. POST /api/files/upload
  @Post('upload')
  @RequirePermission('files', 'create')
  @UseInterceptors(FileInterceptor('file', { limits: { fileSize: MAX_FILE_SIZE } }))
  upload(@CurrentTenant() t: RequestTenantContext, @UploadedFile() file: UploadedMulterFile, @Body('leadId') leadId?: string, @Body('contactId') contactId?: string, @Body('accountId') accountId?: string, @Body('dealId') dealId?: string, @Body('projectId') projectId?: string, @Body('description') description?: string) {
    return this.files.upload(t, file, { leadId, contactId, accountId, dealId, projectId, description });
  }

  // Deletes a file attachment from MySQL. DELETE /api/files/:id
  @Delete(':id')
  @RequirePermission('files', 'delete')
  remove(@CurrentTenant() t: RequestTenantContext, @CurrentUser() actor: CrmActor, @Param('id') id: string) {
    return this.files.remove(t, actor, id);
  }
}
