import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ProductsService } from './products.service';
import { CreateProductDto } from './dto/create-product.dto';
import { UpdateProductDto } from './dto/update-product.dto';
import { UpsertUserProductDiscountDto } from './dto/user-product-discount.dto';

@Controller('products')
@UseGuards(AuthGuard('jwt'))
export class ProductsController {
  constructor(private readonly productsService: ProductsService) {}

  @Post()
  create(@Body() createProductDto: CreateProductDto) {
    return this.productsService.create(createProductDto);
  }

  @Get()
  findAll() {
    return this.productsService.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.productsService.findOne(id);
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() updateProductDto: UpdateProductDto) {
    return this.productsService.update(id, updateProductDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.productsService.remove(id);
  }

  // ─── Per-User Discount Cap Endpoints ─────────────────────────────────────

  /** GET /products/:productId/user-discounts — list all user caps for this product */
  @Get(':productId/user-discounts')
  getUserDiscounts(@Param('productId') productId: string) {
    return this.productsService.getUserDiscounts(productId);
  }

  /** POST /products/:productId/user-discounts — upsert a user cap */
  @Post(':productId/user-discounts')
  upsertUserDiscount(
    @Param('productId') productId: string,
    @Body() dto: UpsertUserProductDiscountDto,
  ) {
    return this.productsService.upsertUserDiscount(
      productId,
      dto.userId,
      dto.maxDiscountPercentage,
      dto.schemeId ?? null,
    );
  }

  /** DELETE /products/:productId/user-discounts/:discountId — remove a user cap */
  @Delete(':productId/user-discounts/:discountId')
  removeUserDiscount(@Param('discountId') discountId: string) {
    return this.productsService.removeUserDiscount(discountId);
  }
}
