import {
  Controller,
  Get,
  Patch,
  Body,
  Req,
  UseInterceptors,
  ClassSerializerInterceptor,
  UsePipes,
  UseGuards,
} from "@nestjs/common";
import { UsersFacade } from "./application/users.facade";
import { ZodValidationPipe } from "@customer-portal/validation/nestjs";
import {
  updateCustomerProfileRequestSchema,
  type UpdateCustomerProfileRequest,
} from "@customer-portal/domain/auth";
import { addressSchema, type Address } from "@customer-portal/domain/customer";
import type { RequestWithUser } from "@bff/modules/auth/auth.types";
import { SalesforceReadThrottleGuard } from "@bff/integrations/salesforce/guards/salesforce-read-throttle.guard";

@Controller("me")
@UseInterceptors(ClassSerializerInterceptor)
export class UsersController {
  constructor(private usersFacade: UsersFacade) {}

  /**
   * GET /me - Get complete customer profile (includes address)
   * Profile data fetched from WHMCS (single source of truth)
   */
  @UseGuards(SalesforceReadThrottleGuard)
  @Get()
  async getProfile(@Req() req: RequestWithUser) {
    return this.usersFacade.findById(req.user.id);
  }

  /**
   * GET /me/summary - Get dashboard summary
   */
  @UseGuards(SalesforceReadThrottleGuard)
  @Get("summary")
  async getSummary(@Req() req: RequestWithUser) {
    return this.usersFacade.getUserSummary(req.user.id);
  }

  /**
   * GET /me/address - Get customer address only
   */
  @UseGuards(SalesforceReadThrottleGuard)
  @Get("address")
  async getAddress(@Req() req: RequestWithUser): Promise<Address | null> {
    return this.usersFacade.getAddress(req.user.id);
  }

  /**
   * PATCH /me/address - Update address fields
   */
  @Patch("address")
  @UsePipes(new ZodValidationPipe(addressSchema.partial()))
  async updateAddress(
    @Req() req: RequestWithUser,
    @Body() address: Partial<Address>
  ): Promise<Address> {
    return this.usersFacade.updateAddress(req.user.id, address);
  }

  /**
   * PATCH /me - Update customer profile (can update profile fields and/or address)
   * All fields optional - only send what needs to be updated
   * Updates stored in WHMCS (single source of truth)
   *
   * Examples:
   *  - Update name only: { firstname: "John", lastname: "Doe" }
   *  - Update address only: { address1: "123 Main St", city: "Tokyo" }
   *  - Update both: { firstname: "John", address1: "123 Main St" }
   */
  @Patch()
  @UsePipes(new ZodValidationPipe(updateCustomerProfileRequestSchema))
  async updateProfile(
    @Req() req: RequestWithUser,
    @Body() updateData: UpdateCustomerProfileRequest
  ) {
    return this.usersFacade.updateProfile(req.user.id, updateData);
  }
}
