import { Body, Controller, Delete, Get, Param, Patch, Post, Req, UseGuards } from '@nestjs/common';
import { Roles } from '../common/decorators/roles.decorator';
import { JwtAuthGuard } from '../common/guards/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { TrackingService } from '../tracking/tracking.service';
import { CustomersService } from './customers.service';
import { UpsertCustomerDto } from './dto/upsert-customer.dto';

@Controller()
@UseGuards(JwtAuthGuard, RolesGuard)
export class CustomersController {
  constructor(
    private readonly trackingService: TrackingService,
    private readonly customersService: CustomersService,
  ) {}

  @Get('customers')
  @Roles('ADMIN', 'SUPER_ADMIN')
  index() {
    return this.customersService.list();
  }

  @Post('customers')
  @Roles('ADMIN', 'SUPER_ADMIN')
  create(@Body() body: UpsertCustomerDto) {
    return this.customersService.create(body);
  }

  @Patch('customers/:id')
  @Roles('ADMIN', 'SUPER_ADMIN')
  update(@Param('id') id: string, @Body() body: Partial<UpsertCustomerDto>) {
    return this.customersService.update(id, body);
  }

  @Delete('customers/:id')
  @Roles('ADMIN', 'SUPER_ADMIN')
  archive(@Param('id') id: string) {
    return this.customersService.archive(id);
  }

  @Get('customer/orders/:id/tracking')
  @Roles('CUSTOMER')
  orderTracking(@Req() req: { user: { sub: string; role: string } }, @Param('id') id: string) {
    return this.trackingService.getOrderTracking(id, req.user as never);
  }

  @Get('customer/me')
  @Roles('CUSTOMER')
  me(@Req() req: { user: { sub: string; role: string } }) {
    return this.customersService.getOwnProfile(req.user.sub);
  }

  @Patch('customer/me')
  @Roles('CUSTOMER')
  updateMe(@Req() req: { user: { sub: string; role: string } }, @Body() body: { fullName?: string; email?: string; phone?: string }) {
    return this.customersService.updateOwnProfile(req.user.sub, body);
  }

  @Get('customer/me/address')
  @Roles('CUSTOMER')
  address(@Req() req: { user: { sub: string; role: string } }) {
    return this.customersService.getOwnAddress(req.user.sub);
  }

  @Patch('customer/me/address')
  @Roles('CUSTOMER')
  updateAddress(
    @Req() req: { user: { sub: string; role: string } },
    @Body() body: { label?: string; street?: string; number?: string; complement?: string; neighborhood?: string; city?: string; state?: string; zipCode?: string },
  ) {
    return this.customersService.updateOwnAddress(req.user.sub, body);
  }
}
