import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateEnquiryDto } from './dto/create-enquiry.dto';
import { UpdateEnquiryDto } from './dto/update-enquiry.dto';
import { UsersService } from '../users/users.service';
import { user_role } from '@prisma/client';

@Injectable()
export class EnquiriesService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly usersService: UsersService
  ) { }

  create(createEnquiryDto: CreateEnquiryDto) {
    const { productIds, ...data } = createEnquiryDto;
    return this.prisma.enquiry.create({
      data: {
        ...data,
        products: productIds?.length
          ? { connect: productIds.map((id) => ({ id })) }
          : undefined,
      },
      include: {
        products: true,
        client: true,
        user: true,
      },
    });
  }

  async findAll(user: any) {
    if (user.role === user_role.ADMIN) {
      return this.prisma.enquiry.findMany({
        include: {
          products: true,
          client: true,
          user: true,
          quotes: true,
        },
      });
    }

    const subordinateIds = await this.usersService.getSubordinateIds(user.id);
    const allowedUserIds = [user.id, ...subordinateIds];

    return this.prisma.enquiry.findMany({
      where: {
        userId: { in: allowedUserIds }
      },
      include: {
        products: true,
        client: true,
        user: true,
        quotes: true,
      },
    });
  }

  findOne(id: string) {
    return this.prisma.enquiry.findUnique({
      where: { id },
      include: {
        products: true,
        client: true,
        user: true,
        followups: true,
        quotes: true,
      },
    });
  }

  update(id: string, updateEnquiryDto: UpdateEnquiryDto) {
    const { productIds, ...data } = updateEnquiryDto;
    return this.prisma.enquiry.update({
      where: { id },
      data: {
        ...data,
        products: productIds
          ? { set: productIds.map((id) => ({ id })) }
          : undefined,
      },
    });
  }

  remove(id: string) {
    return this.prisma.enquiry.delete({
      where: { id },
    });
  }
}
