import { Injectable } from "@nestjs/common";
import { PrismaPostgresService } from "prisma/postgres/prisma-postgres.service";
import { Result } from "src/common/errors/result-error.factory";
import { EmailToIdResolver } from "src/common/mappers/email-id.mapper";
import { PayPeriodEventService } from "src/time-and-attendance/pay-period/services/pay-period-event.service";

@Injectable()
export class ExpenseDeleteService {
    constructor(
        private readonly prisma: PrismaPostgresService,
        private readonly payPeriodEventService: PayPeriodEventService,
        private readonly emailResolver: EmailToIdResolver,
    ){}

    //_________________________________________________________________
    //                              DELETE
    //_________________________________________________________________
    async deleteExpense(expense_id: number, email: string): Promise<Result<number, string>> {
        // get employee id of employee who made delete request
        const employee = await this.emailResolver.findIdByEmail(email);

        if (!employee.success) return employee;

        // confirm ownership of expense to employee who made request
        const expense = await this.prisma.expenses.findUnique({
            where: { id: expense_id},
            select: {
                timesheet: {
                    select: {
                        employee_id: true,
                    }
                }
            }
        });

        if (!expense || expense.timesheet.employee_id !== employee.data) return { success: false, error: 'EXPENSE_NOT_FOUND'};

        try {
            await this.prisma.$transaction(async (tx) => {
                const expense = await tx.expenses.findUnique({
                    where: { id: expense_id },
                    select: { id: true },
                });
                if (!expense) return { success: false, error: `EXPENSE_NOT_FOUND` };

                await tx.expenses.delete({ where: { id: expense.id } });
                return { success: true, data: expense.id };
            });

            // notify timesheet-approval observers of changes
            this.payPeriodEventService.emit({
                employee_email: email,
                event_type: 'expense',
                action: 'delete',
            });

            return { success: true, data: expense_id };
        } catch (error) {
            return { success: false, error: `EXPENSE_NOT_FOUND` };
        }
    }
}