import { ENV_OPTIONAL_NUMBER_KEYS_MAPPING, SEQUELIZE_INSTANCE_TOKEN } from '@humand-packages/common';
import { Sequelize } from 'sequelize-typescript';
import { Inject, Service } from 'typedi';
import { v7 as uuidv7 } from 'uuid';
import { BaseRepositoryAdapter } from '../../../../../../dbAdapters/baseRepositoryAdapter';
import { TimeTrackingIncidenceNotificationLogForCreation } from '../../../../business/models/timeTracking/timeTrackingIncidenceNotificationLog';
import { TimeTrackingIncidenceNotificationLogDAO } from '../../../dataAccessObjects/timeTracking/timeTrackingIncidenceNotificationLogDAO';
import { TimeTrackingIncidenceNotificationLogRepositoryPort } from '../../../ports/timeTracking/timeTrackingIncidenceNotificationLogRepositoryPort';

@Service()
export class TimeTrackingIncidenceNotificationLogRepositoryAdapter
    extends BaseRepositoryAdapter
    implements TimeTrackingIncidenceNotificationLogRepositoryPort
{
    constructor(
        @Inject(ENV_OPTIONAL_NUMBER_KEYS_MAPPING.BULK_CREATE_CHUNK_SIZE) bulkCreateChunkSize: number,
        @Inject(SEQUELIZE_INSTANCE_TOKEN) sequelize: Sequelize,
    ) {
        super(bulkCreateChunkSize, sequelize);
    }

    public createIfAbsent = async (entry: TimeTrackingIncidenceNotificationLogForCreation): Promise<{ created: boolean }> => {
        const isEntryLevel = entry.entryId !== null;
        const where = isEntryLevel
            ? {
                  instanceId: entry.instanceId,
                  entryId: entry.entryId,
                  incidenceType: entry.incidenceType,
              }
            : {
                  instanceId: entry.instanceId,
                  userId: entry.userId,
                  dateString: entry.dateString,
                  incidenceType: entry.incidenceType,
                  entryId: null,
              };
        const defaults = {
            id: uuidv7(),
            instanceId: entry.instanceId,
            userId: entry.userId,
            dateString: entry.dateString,
            incidenceType: entry.incidenceType,
            entryId: entry.entryId,
        };
        const [, created] = await TimeTrackingIncidenceNotificationLogDAO.findCreateFind({ where, defaults });
        return { created };
    };
}
