import { Body, Controller, Get, Param, Post, Put, Request, UseGuards, Query } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
import { AppTokenGuard } from 'src/app-token.guard';
import { StoreJwtGuard } from './store-jwt.guard';
import { StoreAuthService } from './store-auth.service';
import { StoreLoginDto, StoreRegisterDto, StoreSyncCartDto, StoreUpdateProfileDto } from './store-auth.dto';

@ApiTags('Store Auth')
@ApiSecurity('x-app-key')
@UseGuards(AppTokenGuard)
@Controller({ path: 'store/auth', version: '1' })
export class StoreAuthController {
  constructor(private readonly service: StoreAuthService) {}

  @Post('register')
  @ApiOperation({ summary: 'Registro de cliente en la tienda' })
  register(@Body() dto: StoreRegisterDto) {
    return this.service.register(dto);
  }

  @Post('login')
  @ApiOperation({ summary: 'Login de cliente de tienda — devuelve JWT de 30 días' })
  login(@Body() dto: StoreLoginDto) {
    return this.service.login(dto);
  }

  @Get('me')
  @ApiBearerAuth()
  @UseGuards(StoreJwtGuard)
  @ApiOperation({ summary: 'Perfil del cliente autenticado' })
  me(@Request() req: { user: { id: string } }) {
    return this.service.me(req.user.id);
  }

  @Put('me')
  @ApiBearerAuth()
  @UseGuards(StoreJwtGuard)
  @ApiOperation({ summary: 'Actualizar perfil del cliente autenticado' })
  updateProfile(@Request() req: { user: { id: string } }, @Body() dto: StoreUpdateProfileDto) {
    return this.service.updateProfile(req.user.id, dto);
  }

  @Get('orders')
  @ApiBearerAuth()
  @UseGuards(StoreJwtGuard)
  @ApiOperation({ summary: 'Historial de pedidos del cliente autenticado' })
  getOrders(@Request() req: { user: { id: string } }) {
    return this.service.getOrders(req.user.id);
  }

  @Post('cart/sync')
  @ApiBearerAuth()
  @UseGuards(StoreJwtGuard)
  @ApiOperation({ summary: 'Sincronizar carrito local → BD (al iniciar sesión)' })
  syncCart(@Request() req: { user: { id: string } }, @Body() dto: StoreSyncCartDto) {
    return this.service.syncCart(req.user.id, dto);
  }

  @Get('cart')
  @ApiBearerAuth()
  @UseGuards(StoreJwtGuard)
  @ApiOperation({ summary: 'Obtener carrito guardado del cliente' })
  getCart(@Request() req: { user: { id: string } }) {
    return this.service.getCart(req.user.id);
  }

  @Post('resenas/:productoId')
  @ApiBearerAuth()
  @UseGuards(StoreJwtGuard)
  @ApiOperation({ summary: 'Publicar o actualizar reseña del cliente para un producto' })
  submitReview(
    @Request() req: { user: { id: string } },
    @Param('productoId') productoId: string,
    @Body() body: { rating: number; comment?: string },
  ) {
    return this.service.submitReview(req.user.id, productoId, body);
  }
}
