import {
  Controller,
  Post,
  Get,
  Body,
  Param,
  Query,
  UseGuards,
  Req,
  HttpCode,
  HttpStatus,
  NotFoundException,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
  ApiParam,
} from '@nestjs/swagger';
import { PlantingApplicationService } from '../../application/services/planting-application.service';
import { CreatePlantingOrderDto } from '../dto/request/create-planting-order.dto';
import { SelectProvinceCityDto } from '../dto/request/select-province-city.dto';
import { PaginationDto } from '../dto/request/pagination.dto';
import {
  CreateOrderResponse,
  SelectProvinceCityResponse,
  ConfirmProvinceCityResponse,
  PayOrderResponse,
  PlantingOrderResponse,
} from '../dto/response/planting-order.response';
import { JwtAuthGuard } from '../guards/jwt-auth.guard';

interface AuthenticatedRequest {
  user: { id: string; accountSequence: string };
}

@ApiTags('认种订单')
@ApiBearerAuth()
@Controller('planting')
@UseGuards(JwtAuthGuard)
export class PlantingOrderController {
  constructor(
    private readonly plantingService: PlantingApplicationService,
  ) {}

  @Post('orders')
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({ summary: '创建认种订单' })
  @ApiResponse({
    status: HttpStatus.CREATED,
    description: '订单创建成功',
    type: CreateOrderResponse,
  })
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, description: '参数错误' })
  @ApiResponse({ status: HttpStatus.UNAUTHORIZED, description: '未授权' })
  async createOrder(
    @Req() req: AuthenticatedRequest,
    @Body() dto: CreatePlantingOrderDto,
  ): Promise<CreateOrderResponse> {
    const userId = BigInt(req.user.id);
    const accountSequence = req.user.accountSequence;
    return this.plantingService.createOrder(userId, accountSequence, dto.treeCount);
  }

  @Post('orders/:orderNo/select-province-city')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '选择省市' })
  @ApiParam({ name: 'orderNo', description: '订单号' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '省市选择成功',
    type: SelectProvinceCityResponse,
  })
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, description: '参数错误' })
  @ApiResponse({ status: HttpStatus.NOT_FOUND, description: '订单不存在' })
  async selectProvinceCity(
    @Req() req: AuthenticatedRequest,
    @Param('orderNo') orderNo: string,
    @Body() dto: SelectProvinceCityDto,
  ): Promise<SelectProvinceCityResponse> {
    const userId = BigInt(req.user.id);
    return this.plantingService.selectProvinceCity(
      orderNo,
      userId,
      dto.provinceCode,
      dto.provinceName,
      dto.cityCode,
      dto.cityName,
    );
  }

  @Post('orders/:orderNo/confirm-province-city')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '确认省市选择（5秒后调用）' })
  @ApiParam({ name: 'orderNo', description: '订单号' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '省市确认成功',
    type: ConfirmProvinceCityResponse,
  })
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, description: '还需等待5秒' })
  @ApiResponse({ status: HttpStatus.NOT_FOUND, description: '订单不存在' })
  async confirmProvinceCity(
    @Req() req: AuthenticatedRequest,
    @Param('orderNo') orderNo: string,
  ): Promise<ConfirmProvinceCityResponse> {
    const userId = BigInt(req.user.id);
    return this.plantingService.confirmProvinceCity(orderNo, userId);
  }

  @Post('orders/:orderNo/pay')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '支付认种订单' })
  @ApiParam({ name: 'orderNo', description: '订单号' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '支付成功',
    type: PayOrderResponse,
  })
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, description: '余额不足或状态错误' })
  @ApiResponse({ status: HttpStatus.NOT_FOUND, description: '订单不存在' })
  async payOrder(
    @Req() req: AuthenticatedRequest,
    @Param('orderNo') orderNo: string,
  ): Promise<PayOrderResponse> {
    const userId = BigInt(req.user.id);
    return this.plantingService.payOrder(orderNo, userId, req.user.accountSequence);
  }

  @Get('orders')
  @ApiOperation({ summary: '查询我的订单列表' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '订单列表',
    type: [PlantingOrderResponse],
  })
  async getUserOrders(
    @Req() req: AuthenticatedRequest,
    @Query() pagination: PaginationDto,
  ): Promise<PlantingOrderResponse[]> {
    const userId = BigInt(req.user.id);
    return this.plantingService.getUserOrders(
      userId,
      pagination.page,
      pagination.pageSize,
    );
  }

  @Get('orders/:orderNo')
  @ApiOperation({ summary: '查询订单详情' })
  @ApiParam({ name: 'orderNo', description: '订单号' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '订单详情',
    type: PlantingOrderResponse,
  })
  @ApiResponse({ status: HttpStatus.NOT_FOUND, description: '订单不存在' })
  async getOrderDetail(
    @Req() req: AuthenticatedRequest,
    @Param('orderNo') orderNo: string,
  ): Promise<PlantingOrderResponse> {
    const userId = BigInt(req.user.id);
    const order = await this.plantingService.getOrderDetail(orderNo, userId);
    if (!order) {
      throw new NotFoundException('订单不存在');
    }
    return order;
  }

  @Post('orders/:orderNo/cancel')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '取消订单' })
  @ApiParam({ name: 'orderNo', description: '订单号' })
  @ApiResponse({
    status: HttpStatus.OK,
    description: '取消成功',
  })
  @ApiResponse({ status: HttpStatus.BAD_REQUEST, description: '订单状态不允许取消' })
  @ApiResponse({ status: HttpStatus.NOT_FOUND, description: '订单不存在' })
  async cancelOrder(
    @Req() req: AuthenticatedRequest,
    @Param('orderNo') orderNo: string,
  ): Promise<{ success: boolean }> {
    const userId = BigInt(req.user.id);
    return this.plantingService.cancelOrder(orderNo, userId);
  }
}
