import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { v4 as uuid } from 'uuid';

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

    async createFromOpportunity(opportunityId: string, details?: string) {
        return this.prisma.workOrder.create({
            data: {
                id: uuid(),
                opportunityId,
                details,
                status: 'IN_PROGRESS',
                updatedAt: new Date()
            }
        });
    }

    async findAllByOpportunity(opportunityId: string) {
        return this.prisma.workOrder.findMany({
            where: { opportunityId },
            include: { payments: true }
        });
    }

    async addPayment(workOrderId: string, amount: number, mode: string) {
        return this.prisma.payment.create({
            data: {
                id: uuid(),
                workOrderId,
                amount,
                mode,
                status: 'COMPLETED',
                updatedAt: new Date()
            }
        });
    }

    async getStats() {
        const totalWorkOrders = await this.prisma.workOrder.count();
        const pendingPayments = await this.prisma.payment.aggregate({
            where: { status: 'PENDING' },
            _sum: { amount: true }
        });
        return { totalWorkOrders, pendingPayments: pendingPayments._sum.amount || 0 };
    }
}
