import { Injectable } from '@nestjs/common';
import { PrismaService } from '../database/prisma.service';
import { CreateOrderCustomerDto } from './dto/create-order-customer.dto';
import { UpdateCustomerDto } from './dto/update-customer.dto';

@Injectable()
export class CustomersService {
  constructor(private readonly prisma: PrismaService) {}

  async findAll() {
    return this.prisma.customer.findMany({
      orderBy: {
        createdAt: 'desc',
      },
      include: {
        lead: true,
      },
    });
  }

  async findOne(id: number) {
    return this.prisma.customer.findUnique({
      where: {
        id,
      },
      include: {
        lead: true,
      },
    });
  }

  async createOrder(dto: CreateOrderCustomerDto) {
    let lead = await this.prisma.lead.findUnique({
      where: {
        phone: dto.phone,
      },
    });

    if (!lead) {
      lead = await this.prisma.lead.create({
        data: {
          name: dto.name,
          product: dto.product,
          phone: dto.phone,
          email: dto.email,
          status: dto.status,
          operator: dto.operator,
          comment: dto.comment,
          source: dto.source,
        },
      });
    }

    const customer = await this.prisma.customer.create({
      data: {
        name: dto.name,
        product: dto.product,
        phone: dto.phone,
        email: dto.email,
        status: dto.status,
        operator: dto.operator,
        comment: dto.comment,
        source: dto.source,
        leadId: lead.id,
      },
      include: {
        lead: true,
      },
    });

    return customer;
  }

  async update(id: number, dto: UpdateCustomerDto) {
    return this.prisma.customer.update({
      where: {
        id,
      },
      data: dto,
      include: {
        lead: true,
      },
    });
  }

}
