import { Injectable } from "@nestjs/common";

import { PrismaPostgresService } from "prisma/postgres/prisma-postgres.service";

import { SchedulePresetsDto, SchedulePresetShiftsDto } from "../schedule-presets.dto";

import { Result } from "src/common/errors/result-error.factory";

@Injectable()
export class SchedulePresetsGetService {
    constructor(
        private readonly prisma: PrismaPostgresService,
    ) { }

    async getSchedulePresets(): Promise<Result<SchedulePresetsDto[], string>> {
        try {
            const presets = await this.prisma.schedulePresets.findMany({
                orderBy: [{ name: 'asc' }],
                include: {
                    shifts: {
                        orderBy: [{ week_day: 'asc' }, { start_time: 'asc' }],
                        include: { bank_code: { select: { type: true } } },
                    },
                },
            });
            const hhmm = (date: Date) => date.toISOString().slice(11, 16);

            const response: SchedulePresetsDto[] = presets.map((preset) => ({
                id: preset.id,
                name: preset.name,
                shifts: preset.shifts.map<Omit<SchedulePresetShiftsDto, 'id'>>((shift) => ({
                    preset_id: shift.preset_id,
                    week_day: shift.week_day,
                    start_time: hhmm(shift.start_time),
                    end_time: hhmm(shift.end_time),
                    is_remote: shift.is_remote,
                    type: shift.bank_code?.type,
                })),
            }));

            return { success: true, data: response };
        } catch (error) {
            return { success: false, error: `SCHEDULE_PRESET_NOT_FOUND` };
        }
    }

}