import { BaseAdapter } from '@humand-packages/common';
import { ScheduledActionsService } from '@humand-packages/scheduled-actions';
import { Service } from 'typedi';
import { v7 } from 'uuid';
import { getConfig } from '../../../../../apiConfig/configSetup';
import { ScheduleCategorizedHoursParams } from '../../../business/models/scheduleCategorizedHoursParams';
import ScheduleCategorizedHoursPort from '../../../business/ports/scheduleCategorizedHoursPort';

@Service()
export class ScheduleCategorizedHoursAdapter extends BaseAdapter implements ScheduleCategorizedHoursPort {
    constructor(private readonly scheduledActionsService: ScheduledActionsService) {
        super();
    }

    schedule = async (params: ScheduleCategorizedHoursParams, deadline?: Date): Promise<void> => {
        const now = new Date();
        const messageBody = JSON.stringify({
            payload: params.payload,
            timestamp: now.toISOString(),
            type: params.type,
            uuid: v7({ msecs: now.getTime() }),
        });

        const queueUrl = getConfig().awsSqsTimeTrackingCategorizedHoursQueueUrl!;
        await this.scheduledActionsService.scheduleAt(deadline ?? now, {
            messageBody,
            queueUrl,
            type: 'SQS_SEND_MESSAGE',
        });
    };

    bulkSchedule = async (scheduleItems: ScheduleCategorizedHoursParams[], deadline?: Date): Promise<void> => {
        if (scheduleItems.length === 0) return;
        const now = new Date();
        const queueUrl = getConfig().awsSqsTimeTrackingCategorizedHoursQueueUrl!;
        const items = scheduleItems.map((params) => ({
            deadline: deadline ?? now,
            scheduledActionConfig: {
                messageBody: JSON.stringify({
                    payload: params.payload,
                    timestamp: now.toISOString(),
                    type: params.type,
                    uuid: v7({ msecs: now.getTime() }),
                }),
                queueUrl,
                type: 'SQS_SEND_MESSAGE' as const,
            },
        }));
        await this.scheduledActionsService.bulkScheduleAt(items);
    };
}
