import { Injectable } from "@nestjs/common";
import { Result } from "src/common/errors/result-error.factory";
import { EmailToIdResolver } from "src/common/mappers/email-id.mapper";
import { ModuleAccess } from "src/identity-and-account/user-module-access/module-acces.dto";
import { PrismaPostgresService } from "prisma/postgres/prisma-postgres.service";


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

    async findModuleAccess(email: string, employee_email?: string): Promise<Result<ModuleAccess, string>> {
        const account_email = employee_email ?? email;
        const user_id = await this.emailResolver.resolveUserIdWithEmail(account_email);
        if (!user_id.success) return { success: false, error: 'EMPLOYEE_NOT_FOUND' };

        const access = await this.prisma.userModuleAccess.findUnique({
            where: { user_id: user_id.data },
            select: {
                timesheets: true,
                timesheets_approval: true,
                employee_list: true,
                employee_management: true,
                personal_profile: true,
                dashboard: true,
            },
        });
        if (!access) return { success: false, error: 'MODULE_ACCESS_NOT_FOUND' };

        const granted_access: ModuleAccess = {
            timesheets: access.timesheets,
            timesheets_approval: access.timesheets_approval,
            employee_list: access.employee_list,
            employee_management: access.employee_management,
            personal_profile: access.personal_profile,
            dashboard: access.dashboard,
        };
        return { success: true, data: granted_access }
    };
}