import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '@/prisma/prisma.service';
import { CreateWorkDto, UpdateWorkDto } from '../dto/work.dto';

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

  async createWork(tenantId: string, dto: CreateWorkDto) {
    const complex = await this.prisma.complex.findFirst({
      where: { id: dto.complexId, tenantId },
    });
    if (!complex) throw new NotFoundException('Complex not found');

    if (dto.contractorId) {
      const supplier = await this.prisma.supplier.findFirst({
        where: { id: dto.contractorId, tenantId },
      });
      if (!supplier) throw new NotFoundException('Contractor not found');
    }

    return this.prisma.workProject.create({
      data: {
        complexId: dto.complexId,
        title: dto.title,
        description: dto.description,
        budget: dto.budget,
        startDate: dto.startDate ? new Date(dto.startDate) : null,
        endDate: dto.endDate ? new Date(dto.endDate) : null,
        contractorId: dto.contractorId,
      },
    });
  }

  async getWorks(tenantId: string | null, complexId: string) {
    return this.prisma.workProject.findMany({
      where: {
        complexId,
        ...(tenantId && { complex: { tenantId } }),
      },
      include: {
        contractor: true,
      },
      orderBy: { createdAt: 'desc' },
    });
  }

  async getWork(tenantId: string | null, workId: string) {
    const work = await this.prisma.workProject.findFirst({
      where: {
        id: workId,
        ...(tenantId && { complex: { tenantId } }),
      },
      include: { contractor: true },
    });
    if (!work) throw new NotFoundException('Work project not found');
    return work;
  }

  async updateWork(tenantId: string | null, workId: string, dto: UpdateWorkDto) {
    const work = await this.prisma.workProject.findFirst({
      where: { id: workId, ...(tenantId && { complex: { tenantId } }) },
    });
    if (!work) throw new NotFoundException('Work project not found');

    if (dto.contractorId) {
      const supplier = await this.prisma.supplier.findFirst({
        where: { id: dto.contractorId, ...(tenantId && { tenantId }) },
      });
      if (!supplier) throw new NotFoundException('Contractor not found');
    }

    return this.prisma.workProject.update({
      where: { id: workId },
      data: {
        ...dto,
        startDate: dto.startDate ? new Date(dto.startDate) : undefined,
        endDate: dto.endDate ? new Date(dto.endDate) : undefined,
      },
    });
  }

  async deleteWork(tenantId: string | null, workId: string) {
    const work = await this.prisma.workProject.findFirst({
      where: { id: workId, ...(tenantId && { complex: { tenantId } }) },
    });
    if (!work) throw new NotFoundException('Work project not found');

    return this.prisma.workProject.delete({
      where: { id: workId },
    });
  }
}
