import { DisplayLanguage, PreferencesDto } from "./preferences.dto";
import { PrismaPostgresService } from "prisma/postgres/prisma-postgres.service";
import { Injectable } from "@nestjs/common";
import { Result } from "src/common/errors/result-error.factory";
import { EmailToIdResolver } from "src/common/mappers/email-id.mapper";

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

    async findPreferences(email: string, employee_email?: string): Promise<Result<PreferencesDto, 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 user_preferences = await this.prisma.preferences.findUnique({
            where: { user_id: user_id.data },
            select: {
                id: true,
                notifications: true,
                is_dark_mode: true,
                display_language: true,
                is_lefty_mode: true,
                is_employee_list_grid: true,
                is_timesheet_approval_grid: true,
            },
        });
        if (!user_preferences) return { success: false, error: 'PREFERENCES_NOT_FOUND' };

        const preferences: PreferencesDto = {
            id: user_preferences.id,
            is_dark_mode: user_preferences.is_dark_mode,
            display_language: user_preferences.display_language ?? DisplayLanguage.FR ,
            is_lefty_mode: user_preferences.is_lefty_mode,
            notifications: user_preferences.notifications,
            is_employee_list_grid: user_preferences.is_employee_list_grid,
            is_timesheet_approval_grid: user_preferences.is_timesheet_approval_grid,
        };
        return { success: true, data: preferences };
    }

    async updatePreferences(email: string, dto: PreferencesDto): Promise<Result<PreferencesDto, string>> {
        const user_id = await this.emailResolver.resolveUserIdWithEmail(email);
        if (!user_id.success) return { success: false, error: user_id.error }

        const updated_preferences: PreferencesDto = await this.prisma.preferences.update({
                where: { user_id: user_id.data },
                data: {
                    notifications: dto.notifications,
                    is_dark_mode: dto.is_dark_mode,
                    display_language: dto.display_language,
                    is_lefty_mode: dto.is_lefty_mode,
                    is_employee_list_grid: dto.is_employee_list_grid,
                    is_timesheet_approval_grid: dto.is_timesheet_approval_grid,
                },
                omit: { user_id: true },
            });
        return { success: true, data: updated_preferences};
    }
}