import {
  Controller,
  Post,
  Body,
  Query,
  UseGuards,
  UseInterceptors,
  UploadedFile,
  BadRequestException,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import {
  ApiTags,
  ApiOperation,
  ApiBearerAuth,
  ApiConsumes,
  ApiBody,
} from '@nestjs/swagger';
import { CurrentUser, JwtPayload } from '../common/decorators';
import { TenantGuard } from '../auth/guards/tenant.guard';
import { singleResponse } from '../common/dto/pagination.dto';
import { ImportService } from './import.service';
import { ImportPreviewQueryDto } from './dto/import-preview.dto';
import { ImportExecuteDto } from './dto/import-execute.dto';

@ApiTags('Import (CSV/Excel)')
@ApiBearerAuth('access-token')
@UseGuards(TenantGuard)
@Controller('import')
export class ImportController {
  constructor(private readonly importService: ImportService) {}

  @Post('preview')
  @ApiOperation({ summary: 'Datei-Vorschau (CSV/XLSX) mit Spalten-Erkennung' })
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        file: { type: 'string', format: 'binary' },
        entityType: { type: 'string', enum: ['contact', 'company'] },
        delimiter: { type: 'string' },
      },
      required: ['file', 'entityType'],
    },
  })
  @UseInterceptors(
    FileInterceptor('file', {
      limits: { fileSize: 10 * 1024 * 1024 }, // 10 MB
      fileFilter: (
        _req: unknown,
        file: Express.Multer.File,
        cb: (error: Error | null, acceptFile: boolean) => void,
      ) => {
        const allowed = [
          'text/csv',
          'application/vnd.ms-excel',
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          'text/plain',
        ];
        if (allowed.includes(file.mimetype)) {
          cb(null, true);
        } else {
          cb(
            new BadRequestException(
              `Dateityp "${file.mimetype}" nicht erlaubt. Nur CSV und Excel.`,
            ),
            false,
          );
        }
      },
    }),
  )
  async preview(
    @UploadedFile() file: Express.Multer.File,
    @Query() query: ImportPreviewQueryDto,
  ) {
    if (!file) {
      throw new BadRequestException('Keine Datei hochgeladen');
    }

    const result = await this.importService.preview(
      file,
      query.entityType,
      query.delimiter,
    );
    return singleResponse(result);
  }

  @Post('execute')
  @ApiOperation({ summary: 'Import ausfuehren (nach Preview)' })
  async execute(
    @CurrentUser() user: JwtPayload,
    @Body() dto: ImportExecuteDto,
  ) {
    const result = await this.importService.execute(
      user.tenantId!,
      user.sub,
      dto,
    );
    return singleResponse(result);
  }
}
