import {
  BadRequestException,
  Body,
  Controller,
  Get,
  HttpCode,
  HttpStatus,
  NotFoundException,
  Param,
  Post,
  Req,
  Request,
  UnauthorizedException,
  UseGuards,
} from '@nestjs/common';
import type { RawBodyRequest } from '@nestjs/common';
import type { Request as ExpressRequest } from 'express';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { SubscriptionGuard } from '../subscription/subscription.guard';
import type { AuthenticatedRequest } from '../../common/interfaces/auth-request.interface';
import { DeliveryService } from './delivery.service';

const CANCEL_REASONS = [
  'customer_cancelled',
  'merchant_cancelled',
  'duplicate',
  'address_problem',
  'other',
];

@Controller('api/deliveries')
@UseGuards(JwtAuthGuard, SubscriptionGuard)
export class DeliveryController {
  constructor(private readonly deliveryService: DeliveryService) {}

  @Get()
  list(@Request() req: AuthenticatedRequest) {
    return this.deliveryService.listForBusiness(req.user.id);
  }

  @Get('status')
  status(@Request() req: AuthenticatedRequest) {
    return this.deliveryService.getStatus(req.user.id);
  }

  @Get(':orderId/events')
  events(
    @Request() req: AuthenticatedRequest,
    @Param('orderId') orderId: string,
  ) {
    return this.deliveryService.getTimeline(req.user.id, orderId);
  }

  @Post(':orderId/book')
  book(
    @Request() req: AuthenticatedRequest,
    @Param('orderId') orderId: string,
  ) {
    return this.deliveryService.bookForOrder(req.user.id, orderId);
  }

  @Post(':orderId/refresh')
  refresh(
    @Request() req: AuthenticatedRequest,
    @Param('orderId') orderId: string,
  ) {
    return this.deliveryService.refresh(req.user.id, orderId);
  }

  @Post(':orderId/cancel')
  cancel(
    @Request() req: AuthenticatedRequest,
    @Param('orderId') orderId: string,
    @Body() body: { reason?: string; note?: string },
  ) {
    const reason = body?.reason || 'merchant_cancelled';
    if (!CANCEL_REASONS.includes(reason))
      throw new BadRequestException(
        `reason must be one of ${CANCEL_REASONS.join(', ')}`,
      );
    return this.deliveryService.cancel(
      req.user.id,
      orderId,
      reason,
      body?.note,
    );
  }
}

@Controller('webhooks/roadrunner')
export class RoadrunnerWebhookController {
  constructor(private readonly deliveryService: DeliveryService) {}

  @Post()
  @HttpCode(HttpStatus.OK)
  async receive(@Req() req: RawBodyRequest<ExpressRequest>) {
    const raw = req.rawBody ?? Buffer.from(JSON.stringify(req.body ?? {}));
    const ok = await this.deliveryService.handleWebhook(raw, req.headers);
    if (!ok) throw new UnauthorizedException('Invalid signature');
    return { received: true };
  }
}

@Controller('track')
export class PublicTrackingController {
  constructor(private readonly deliveryService: DeliveryService) {}

  @Get(':orderId')
  async getPublicTracking(@Param('orderId') orderId: string) {
    try {
      return await this.deliveryService.getPublicTracking(orderId);
    } catch {
      throw new NotFoundException('Tracking information not found');
    }
  }
}
