import { Controller, Get, Post, Put, Body, Param, Query, UseGuards, Req } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { CouponService } from '../../../application/services/coupon.service';
import {
  CreateCouponDto,
  UpdateCouponStatusDto,
  PurchaseCouponDto,
  ListCouponsQueryDto,
} from '../dto/coupon.dto';

@ApiTags('Coupons')
@Controller('coupons')
export class CouponController {
  constructor(private readonly couponService: CouponService) {}

  @Post()
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  @ApiOperation({ summary: 'Create a coupon (issuer only)' })
  async create(@Req() req: any, @Body() dto: CreateCouponDto) {
    const coupon = await this.couponService.create(req.user.id, {
      ...dto,
      faceValue: String(dto.faceValue),
      currentPrice: String(dto.price),
      issuePrice: String(dto.price),
      expiryDate: new Date(dto.validUntil),
    } as any);
    return { code: 0, data: coupon };
  }

  @Get()
  @ApiOperation({ summary: 'List/search coupons' })
  async list(@Query() query: ListCouponsQueryDto) {
    const result = await this.couponService.list(
      query.page || 1,
      query.limit || 20,
      {
        category: query.category,
        status: query.status,
        search: query.search,
        issuerId: query.issuerId,
      },
    );
    return { code: 0, data: result };
  }

  @Get('my')
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  @ApiOperation({ summary: 'Get current user coupon holdings' })
  async getMyHoldings(@Req() req: any, @Query() query: ListCouponsQueryDto) {
    const result = await this.couponService.getByOwner(
      req.user.id,
      query.page || 1,
      query.limit || 20,
      query.status,
    );
    return { code: 0, data: result };
  }

  @Get('my/summary')
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  @ApiOperation({ summary: 'Get user holdings summary (count + total value + saved)' })
  async getMySummary(@Req() req: any) {
    const summary = await this.couponService.getOwnerSummary(req.user.id);
    return { code: 0, data: summary };
  }

  @Get('search')
  @ApiOperation({ summary: 'Search coupons with keyword, category, and sort' })
  async search(
    @Query('q') q?: string,
    @Query('category') category?: string,
    @Query('sort') sort?: string,
    @Query('page') page?: string,
    @Query('limit') limit?: string,
  ) {
    const result = await this.couponService.search(
      q,
      category,
      sort || 'newest',
      parseInt(page || '1'),
      parseInt(limit || '20'),
    );
    return { code: 0, data: result };
  }

  @Get(':id/nearby-stores')
  @ApiOperation({ summary: 'List stores that accept this coupon' })
  async getNearbyStores(@Param('id') id: string) {
    const stores = await this.couponService.getNearbyStores(id);
    return { code: 0, data: stores };
  }

  @Get(':id/similar')
  @ApiOperation({ summary: 'Find similar coupons (same category, different issuer)' })
  async getSimilar(@Param('id') id: string, @Query('limit') limit?: string) {
    const similar = await this.couponService.findSimilar(id, parseInt(limit || '10'));
    return { code: 0, data: similar };
  }

  @Get(':id')
  @ApiOperation({ summary: 'Get coupon details' })
  async getById(@Param('id') id: string) {
    const coupon = await this.couponService.findById(id);
    return { code: 0, data: coupon };
  }

  @Put(':id/status')
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  @ApiOperation({ summary: 'Update coupon status' })
  async updateStatus(@Param('id') id: string, @Body() dto: UpdateCouponStatusDto) {
    const coupon = await this.couponService.updateStatus(id, dto.status as any);
    return { code: 0, data: coupon };
  }

  @Post(':id/purchase')
  @UseGuards(AuthGuard('jwt'))
  @ApiBearerAuth()
  @ApiOperation({ summary: 'Purchase coupon' })
  async purchase(@Param('id') id: string, @Body() dto: PurchaseCouponDto) {
    const result = await this.couponService.purchase(id, dto.quantity || 1);
    return { code: 0, data: result };
  }
}
