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 { Prisma } from "prisma/postgres/generated/prisma/client/postgres/client";


//change promise to return result pattern
@Injectable()
export class PayPeriodsCommandService {
    constructor(
        private readonly prisma: PrismaPostgresService,
        private readonly emailResolver: EmailToIdResolver,
    ) { }

    //function to approve pay-periods according to selected crew members
    async bulkApproveEmployee(email: string, timesheet_ids: number[], is_approved: boolean): Promise<Result<{ shifts: number, expenses: number }, string>> {
        let shifts: Prisma.BatchPayload;
        let expenses: Prisma.BatchPayload;

        //fetch employee id
        const employee_id = await this.emailResolver.findIdByEmail(email);
        if (!employee_id.success) return { success: false, error: employee_id.error }

        try {
            shifts = await this.prisma.shifts.updateMany({
                where: {
                    timesheet: {
                        id: { in: timesheet_ids },
                        employee_id: employee_id.data,
                    },
                },
                data: {
                    is_approved: is_approved,
                }
            });

            expenses = await this.prisma.expenses.updateMany({
                where: {
                    timesheet: {
                        id: { in: timesheet_ids },
                        employee_id: employee_id.data,
                    },
                },
                data: {
                    is_approved: is_approved,
                }
            });

            await this.prisma.timesheets.updateMany({
                where: {
                    id: { in: timesheet_ids},
                    employee_id: employee_id.data,
                },
                data: {
                    is_approved: is_approved,
                }
            })
        } catch (_error) {
            return { success: false, error: 'UNKNOWN_ERROR_VALIDATING' }
        }

        return { success: true, data: { shifts: shifts.count, expenses: expenses.count}}
    }
}