import {
  Body,
  ConflictException,
  Controller,
  Delete,
  Get,
  Param,
  ParseIntPipe,
  Patch,
  Post,
  Query,
} from '@nestjs/common';
import { LeadsService } from './leads.service';
import { CreateLeadDto } from './dto/create-lead.dto';
import { LeadFilterDto } from './dto/lead-filter.dto';
import { UpdateLeadDto } from './dto/update-lead.dto';

@Controller('leads')
export class LeadsController {
  constructor(private readonly leadsService: LeadsService) {}

  @Get()
  async findAll(@Query() filters: LeadFilterDto) {
    return this.leadsService.findAll(filters);
  }

  @Get(':id')
  async findOne(@Param('id', ParseIntPipe) id: number) {
    return this.leadsService.findOne(id);
  }

  @Post()
  async create(@Body() dto: CreateLeadDto) {
    try {
      return await this.leadsService.create(dto);
    } catch (error: any) {
      if (error?.code === 'P2002') {
        throw new ConflictException(
          'A lead with this phone number already exists',
        );
      }

      throw error;
    }
  }

  @Patch(':id')
  async update(
    @Param('id', ParseIntPipe) id: number,
    @Body() dto: UpdateLeadDto,
  ) {
    try {
      return await this.leadsService.update(id, dto);
    } catch (error: any) {
      if (error?.code === 'P2002') {
        throw new ConflictException(
          'A lead with this phone number already exists',
        );
      }

      throw error;
    }
  }

  @Delete(':id')
  async remove(@Param('id', ParseIntPipe) id: number) {
    return this.leadsService.remove(id);
  }
}
