import { BaseController, LoggerPort } from '@humand-packages/common';
import { NextFunction, Request } from 'express';
import { OK } from 'http-status-codes';
import { Service } from 'typedi';
import { DeprecatedHumandResponse } from '../../../../types/locals';
import { PermissionsService } from '../../../permissions/business/services/permissionsService';
import TimeTrackingSettingService from '../../business/services/setting';
import { TimeTrackingSettingUpdateVC } from '../validationClasses/timeTrackingSettingUpdateVC';

@Service()
export class TimeTrackingSettingController extends BaseController {
    constructor(
        private readonly settingService: TimeTrackingSettingService,
        private readonly permissionService: PermissionsService,
        logger: LoggerPort,
    ) {
        super(logger);
    }

    public getByInstanceId = async (_req: Request, res: DeprecatedHumandResponse, next: NextFunction): Promise<void> => {
        const { loggedUser } = res.locals;
        await this.endpointHandlerWithGenerics(next, async () => {
            this.permissionService.validateViewTimeTrackingSettings(loggedUser);
            const setting = await this.settingService.getByInstanceId(loggedUser.getInstanceId());
            res.json(setting);
            res.status(OK).end();
        });
    };

    public update = async (_req: Request, res: DeprecatedHumandResponse, next: NextFunction): Promise<void> => {
        const { loggedUser } = res.locals;
        const params = res.locals.bodyParams as TimeTrackingSettingUpdateVC;
        await this.endpointHandlerWithGenerics(next, async () => {
            this.permissionService.validateManageTimeTracking(loggedUser);
            const updated = await this.settingService.update(loggedUser.getInstanceId(), params);
            res.json(updated);
            res.status(OK).end();
        });
    };
}
