import {
  Controller,
  Get,
  Post,
  Delete,
  Param,
  Body,
  Query,
  UseGuards,
  HttpStatus,
  ParseUUIDPipe,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiQuery } from '@nestjs/swagger';
import { FavoritesService } from './favorites.service';
import { CreateFavoriteDto } from './dto/create-favorite.dto';
import { JwtAuthGuard } from '../common/guards/jwt-auth.guard';
import { CurrentUser } from '../common/decorators/current-user.decorator';

@ApiTags('Favorites')
@Controller('favorites')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
export class FavoritesController {
  constructor(private readonly favoritesService: FavoritesService) {}

  @Get()
  @ApiOperation({ summary: 'Get user favorites' })
  @ApiQuery({ name: 'page', required: false, type: Number })
  @ApiQuery({ name: 'limit', required: false, type: Number })
  async findAll(
    @CurrentUser('id') userId: string,
    @Query('page') page: string = '1',
    @Query('limit') limit: string = '20',
  ) {
    const result = await this.favoritesService.findAllByUser(userId, {
      page: Math.max(1, parseInt(page, 10) || 1),
      limit: Math.min(100, Math.max(1, parseInt(limit, 10) || 20)),
    });

    return {
      ...result,
      message: 'Favorites retrieved successfully',
      statusCode: HttpStatus.OK,
    };
  }

  @Post()
  @ApiOperation({ summary: 'Add to favorites' })
  async create(
    @CurrentUser('id') userId: string,
    @Body() createFavoriteDto: CreateFavoriteDto,
  ) {
    const favorite = await this.favoritesService.create(userId, createFavoriteDto);
    return {
      data: favorite,
      message: 'Added to favorites successfully',
      statusCode: HttpStatus.CREATED,
    };
  }

  @Delete(':id')
  @ApiOperation({ summary: 'Remove from favorites' })
  async remove(
    @CurrentUser('id') userId: string,
    @Param('id', ParseUUIDPipe) id: string,
  ) {
    await this.favoritesService.remove(id, userId);
    return {
      data: null,
      message: 'Removed from favorites successfully',
      statusCode: HttpStatus.OK,
    };
  }
}
