import { Controller, Post, Body, UploadedFile, UseInterceptors, HttpException, HttpStatus, UseGuards } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { UploadService } from './upload.service.js';
import { ApiKeyGuard } from '../guards/api-key.guard.js';
import * as path from 'path';

@Controller('upload')
@UseGuards(ApiKeyGuard)
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}

  @Post('mdb')
  @UseInterceptors(FileInterceptor('file_mdb'))
  async uploadMdb(
    @Body('lokasi') lokasi: string,
    @UploadedFile() file: any
  ) {
    if (!lokasi || !/^[a-zA-Z0-9_-]+$/.test(lokasi)) {
      throw new HttpException({ status: 'error', message: 'Format lokasi tidak valid atau kosong' }, HttpStatus.BAD_REQUEST);
    }

    if (!file) {
      throw new HttpException({ status: 'error', message: 'File MDB tidak ditemukan dalam request. Pastikan menggunakan field name: file_mdb' }, HttpStatus.BAD_REQUEST);
    }

    const ext = path.extname(file.originalname).toLowerCase();
    if (ext !== '.mdb') {
      throw new HttpException({ status: 'error', message: 'Hanya file berektensi .mdb yang diizinkan!' }, HttpStatus.BAD_REQUEST);
    }

    try {
      const result = await this.uploadService.processUpload(lokasi, file.path);
      return result;
    } catch (error) {
      throw new HttpException({ status: 'error', message: ((error as any).message || 'Gagal menyimpan file') }, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}
