import { Prisma, PrismaClient } from "@prisma/client";
import { PrismaPostgresService } from "prisma/postgres/prisma-postgres.service";
import { Result } from "src/common/errors/result-error.factory";

type Tx = Prisma.TransactionClient | PrismaClient;

interface ShiftKey {
    timesheet_id: number;
    date: Date;
    start_time: Date;
    end_time: Date;
    bank_code_id: number;
    is_remote: boolean;
    comment?: string | null;
}

export class ShiftIdResolver {
    constructor(private readonly prisma: PrismaPostgresService) { }

    readonly findShiftIdByData = async (key: ShiftKey, client?: Tx
    ): Promise<Result<number, string>> => {
        const db = (client ?? this.prisma) as PrismaClient;
        const shift = await db.shifts.findFirst({
            where: {
                timesheet_id: key.timesheet_id,
                bank_code_id: key.bank_code_id,
                date: key.date,
                start_time: key.start_time,
                end_time: key.end_time,
                is_remote: key.is_remote,
                comment: key.comment,
            },
            select: { id: true },
        });
        if (!shift) return { success: false, error: `SHIFT_NOT_FOUND` }

        return { success: true, data: shift.id };
    };
}