import { TimeTrackingEntryMessage } from '@humand/desert-eagle-grpc-ts-client';
import { AutoCloseEntryResult } from '../../../business/models/timeTracking/timeTrackingHighAvailability';
import { TimeTrackingEntry } from '../../../business/models/timeTrackingEntry';
import { AutoCloseEntryStatus } from '../../constants/timeTracking/autoCloseEntryStatus';

export const timeTrackingEntryToTimeTrackingEntryGrpc = (
    entry: Partial<TimeTrackingEntry>,
    botAppId?: number,
): TimeTrackingEntryMessage.TimeTrackingEntryMessage => {
    return {
        type: entry.type!,
        userId: entry.userId!,
        time: entry.time,
        siteId: entry.siteId || undefined,
        source: entry.source!,
        latitude: entry.location?.latitude,
        longitude: entry.location?.longitude,
        comment: entry.comment || undefined,
        facialRecognitionSkipped: entry.facialRecognitionSkipped || false,
        createdBy: entry.createdBy || undefined,
        updatedBy: entry.updatedBy || undefined,
        createdAt: entry.createdAt || undefined,
        updatedAt: entry.updatedAt || undefined,
        botAppId,
        instanceId: entry.instanceId!,
        eventTime: entry.eventTime || undefined,
        entryId: entry.desertEagleEntryId ?? undefined,
        summaryId: entry.summaryId || undefined,
        locationIncidence: entry.locationIncidence || undefined,
        isRemoteWork: entry.isRemoteWork ?? undefined,
        location: entry.location
            ? {
                  latitude: entry.location.latitude,
                  longitude: entry.location.longitude,
              }
            : undefined,
    };
};

export const autoCloseEntryResultToAutoCloseEntryResultGrpc = (result: TimeTrackingEntryMessage.AutoCloseEntryResult): AutoCloseEntryResult => {
    const status = mapGrpcStatusToDomain(result.status);

    return {
        index: result.index,
        status: status,
        ...(status === AutoCloseEntryStatus.AUTO_CLOSE_ENTRY_STATUS_CREATED && { entryId: result.entryId }),
    } as AutoCloseEntryResult;
};

const mapGrpcStatusToDomain = (status: TimeTrackingEntryMessage.AutoCloseEntryStatus): AutoCloseEntryStatus => {
    switch (status) {
        case TimeTrackingEntryMessage.AutoCloseEntryStatus.AUTO_CLOSE_ENTRY_STATUS_CREATED:
            return AutoCloseEntryStatus.AUTO_CLOSE_ENTRY_STATUS_CREATED;
        case TimeTrackingEntryMessage.AutoCloseEntryStatus.AUTO_CLOSE_ENTRY_STATUS_IGNORED_OLDER_THAN_CURRENT:
            return AutoCloseEntryStatus.AUTO_CLOSE_ENTRY_STATUS_IGNORED_OLDER_THAN_CURRENT;
        case TimeTrackingEntryMessage.AutoCloseEntryStatus.AUTO_CLOSE_ENTRY_STATUS_UNSPECIFIED:
        default:
            return AutoCloseEntryStatus.AUTO_CLOSE_ENTRY_STATUS_UNSPECIFIED;
    }
};
