import { BaseController, ENV_OPTIONAL_NUMBER_KEYS_MAPPING, LoggerPort } from '@humand-packages/common';
import { NextFunction, Request } from 'express';
import { OK } from 'http-status-codes';
import { Inject, Service } from 'typedi';
import { PortsDI } from '../../../../config/portsDI';
import { DeprecatedHumandResponse } from '../../../../types/locals';
import { PermissionsService } from '../../../permissions/business/services/permissionsService';
import { UserDAO } from '../../../users/infrastructure/dataAccessObjects/userDAO';
import { userDAOtoUser } from '../../../users/infrastructure/mappers/usersMapper';
import { TimeTrackingKioskLinkPort } from '../../business/ports/timeTrackingKioskLinkPort';
import { TimeTrackingKioskLinkCodeVC } from '../validationClasses/timeTrackingKioskLinkCodeVC';
import { TimeTrackingKioskLinkValidateCodeVC } from '../validationClasses/timeTrackingKioskLinkValidateCodeVC';

@Service()
export class TimeTrackingKioskLinkController extends BaseController {
    constructor(
        @PortsDI(TimeTrackingKioskLinkPort) private readonly timeTrackingKioskLinkService: TimeTrackingKioskLinkPort,
        private readonly permissionService: PermissionsService,
        @Inject(ENV_OPTIONAL_NUMBER_KEYS_MAPPING.NOTIFICATION_DELAY) notificationDelay: number,
        logger: LoggerPort,
    ) {
        super(logger, notificationDelay);
    }

    public generateCode = async (_req: Request, res: DeprecatedHumandResponse, next: NextFunction): Promise<void> => {
        await this.endpointHandlerWithGenerics(next, async () => {
            const kioskLink = await this.timeTrackingKioskLinkService.create();
            res.json(kioskLink);
            res.status(OK).end();
        });
    };

    public linkCode = async (_req: Request, res: DeprecatedHumandResponse, next: NextFunction): Promise<void> => {
        const { id, loggedUser } = res.locals;
        const user = userDAOtoUser(loggedUser as UserDAO);
        const params = res.locals.bodyParams as TimeTrackingKioskLinkCodeVC;
        await this.endpointHandlerWithGenerics(next, async () => {
            this.permissionService.validateManageTimeTracking(user);
            const kioskLinked = await this.timeTrackingKioskLinkService.linkCode(id, user, params.code);
            res.json(kioskLinked);
            res.status(OK).end();
        });
    };

    public validateCode = async (_req: Request, res: DeprecatedHumandResponse, next: NextFunction): Promise<void> => {
        const params = res.locals.bodyParams as TimeTrackingKioskLinkValidateCodeVC;
        await this.endpointHandlerWithGenerics(next, async () => {
            const linkData = await this.timeTrackingKioskLinkService.validateCode(params.id, params.code);
            res.json(linkData);
            res.status(OK).end();
        });
    };
}
