import { BadRequestException, Body, Controller, Delete, Get, Param, Patch, Post, Req, UploadedFile, UseGuards, UseInterceptors } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { memoryStorage } from 'multer';
import { Roles } from '../common/decorators/roles.decorator';
import { JwtAuthGuard } from '../common/guards/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { StorageService } from '../storage/storage.service';
import { TrackingService } from '../tracking/tracking.service';
import { UpdateMyRestaurantDto } from './dto/update-my-restaurant.dto';
import { UpsertRestaurantDto } from './dto/upsert-restaurant.dto';
import { RestaurantsService } from './restaurants.service';

@Controller()
@UseGuards(JwtAuthGuard, RolesGuard)
export class RestaurantsController {
  constructor(
    private readonly trackingService: TrackingService,
    private readonly restaurantsService: RestaurantsService,
    private readonly storageService: StorageService,
  ) {}

  @Get('restaurants')
  @Roles('ADMIN', 'SUPER_ADMIN')
  index() {
    return this.restaurantsService.list();
  }

  @Post('restaurants')
  @Roles('ADMIN', 'SUPER_ADMIN')
  create(@Body() body: UpsertRestaurantDto) {
    return this.restaurantsService.create(body);
  }

  @Patch('restaurants/:id')
  @Roles('ADMIN', 'SUPER_ADMIN')
  update(@Param('id') id: string, @Body() body: Partial<UpsertRestaurantDto>) {
    return this.restaurantsService.update(id, body);
  }

  @Delete('restaurants/:id')
  @Roles('ADMIN', 'SUPER_ADMIN')
  archive(@Param('id') id: string) {
    return this.restaurantsService.archive(id);
  }

  @Get('restaurant/profile')
  @Roles('RESTAURANT')
  profile(@Req() req: { user: { sub: string } }) {
    return this.restaurantsService.getByUserId(req.user.sub);
  }

  @Patch('restaurant/profile')
  @Roles('RESTAURANT')
  updateProfile(@Req() req: { user: { sub: string } }, @Body() body: UpdateMyRestaurantDto) {
    return this.restaurantsService.updateByUserId(req.user.sub, body);
  }

  @Post('restaurant/profile/uploads/:field')
  @Roles('RESTAURANT')
  @UseInterceptors(FileInterceptor('file', { storage: memoryStorage() }))
  async uploadRestaurantDocument(
    @Req() req: { user: { sub: string } },
    @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 restaurante.');
    }
    const stored = await this.storageService.savePublicFile(file, `restaurant/${field}`);
    return this.restaurantsService.assignUploadedDocument(req.user.sub, field as never, stored.url);
  }

  @Get('restaurant/orders/:id/tracking')
  @Roles('RESTAURANT')
  orderTracking(@Req() req: { user: { sub: string; role: string } }, @Param('id') id: string) {
    return this.trackingService.getOrderTracking(id, req.user as never);
  }
}
