import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '@/prisma/prisma.service';
import { CreateContractDto, UpdateContractDto } from '../dto/contract.dto';

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

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

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

    return this.prisma.contract.create({
      data: {
        complexId: dto.complexId,
        supplierId: dto.supplierId,
        title: dto.title,
        category: dto.category,
        startDate: new Date(dto.startDate),
        endDate: dto.endDate ? new Date(dto.endDate) : null,
        autoRenew: dto.autoRenew || false,
        amount: dto.amount,
        billingFreq: dto.billingFreq,
        documentUrl: dto.documentUrl,
        notes: dto.notes,
      },
    });
  }

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

  async getContract(tenantId: string | null, contractId: string) {
    const contract = await this.prisma.contract.findFirst({
      where: {
        id: contractId,
        ...(tenantId && { complex: { tenantId } }),
      },
      include: { supplier: true },
    });
    if (!contract) throw new NotFoundException('Contract not found');
    return contract;
  }

  async updateContract(tenantId: string | null, contractId: string, dto: UpdateContractDto) {
    const contract = await this.prisma.contract.findFirst({
      where: { id: contractId, ...(tenantId && { complex: { tenantId } }) },
    });
    if (!contract) throw new NotFoundException('Contract not found');

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

  async deleteContract(tenantId: string | null, contractId: string) {
    const contract = await this.prisma.contract.findFirst({
      where: { id: contractId, ...(tenantId && { complex: { tenantId } }) },
    });
    if (!contract) throw new NotFoundException('Contract not found');

    return this.prisma.contract.delete({
      where: { id: contractId },
    });
  }
}
