import { Body, Controller, Param, Post, UploadedFile, UseInterceptors, BadRequestException } from '@nestjs/common';
import { AccountStatus } from '@prisma/client';
import { FileInterceptor } from '@nestjs/platform-express';
import { memoryStorage } from 'multer';
import { StorageService } from '../storage/storage.service';
import { UpsertRestaurantDto } from './dto/upsert-restaurant.dto';
import { RestaurantsService } from './restaurants.service';

@Controller('public/restaurants')
export class PublicRestaurantsController {
  constructor(
    private readonly restaurantsService: RestaurantsService,
    private readonly storageService: StorageService,
  ) {}

  @Post('register')
  register(@Body() body: UpsertRestaurantDto) {
    return this.restaurantsService.create({
      ...body,
      status: AccountStatus.PENDING,
      documentReviewNotes: undefined,
    });
  }

  @Post('uploads/:field')
  @UseInterceptors(FileInterceptor('file', { storage: memoryStorage() }))
  async uploadDocument(
    @Param('field') field: string,
    @UploadedFile() file: Express.Multer.File | undefined,
  ) {
    const allowedFields = new Set([
      'companyContractUrl',
      'businessLicenseUrl',
      'ownerDocumentUrl',
      'bankProofUrl',
      'logoUrl',
      'coverImageUrl',
    ]);

    if (!allowedFields.has(field)) {
      throw new BadRequestException('Campo de upload nao permitido para cadastro de restaurante.');
    }

    return this.storageService.savePublicFile(file, `restaurant-signup/${field}`);
  }
}
