import {
    TimeTrackingPolicyApprovalStep,
    TimeTrackingPolicyApprovalStepForCreation,
} from '../../../../business/models/policies/approvalSteps/timeTrackingPolicyApprovalStep';
import { TimeTrackingPolicyApprovalStepDAO } from '../../../dataAccessObjects/policies/approvalSteps/timeTrackingPolicyApprovalStepDAO';
import { timeTrackingPolicyApprovalStepResponsibleRelationDAOToModel } from './responsibles/relationMapper';
import { timeTrackingPolicyApprovalStepResponsibleSegmentationItemDAOToModel } from './responsibles/segmentationItemMapper';
import { timeTrackingPolicyApprovalStepResponsibleUserDAOToModel } from './responsibles/userMapper';

export const timeTrackingPolicyApprovalStepDAOToModel = (dao: TimeTrackingPolicyApprovalStepDAO | undefined): TimeTrackingPolicyApprovalStep => {
    if (!dao) return dao as unknown as TimeTrackingPolicyApprovalStep;
    return new TimeTrackingPolicyApprovalStep({
        createdAt: dao.createdAt,
        deletedAt: dao.deletedAt,
        designatedReviewer: dao.designatedReviewer,
        id: dao.id,
        instanceId: dao.instanceId,
        policyId: dao.policyId,
        position: dao.position,
        responsibleRelations: dao.responsibleRelations?.map(timeTrackingPolicyApprovalStepResponsibleRelationDAOToModel),
        responsibleSegmentationItems: dao.responsibleSegmentationItems?.map(timeTrackingPolicyApprovalStepResponsibleSegmentationItemDAOToModel),
        responsibleUsers: dao.responsibleUsers?.map(timeTrackingPolicyApprovalStepResponsibleUserDAOToModel),
        updatedAt: dao.updatedAt,
    });
};

export const timeTrackingPolicyApprovalStepModelToDAO = (
    approvalStep: TimeTrackingPolicyApprovalStep | TimeTrackingPolicyApprovalStepForCreation,
) => {
    if (!approvalStep) return approvalStep as unknown as TimeTrackingPolicyApprovalStepDAO;
    const isAlreadyCreated = approvalStep instanceof TimeTrackingPolicyApprovalStep;
    const dao = TimeTrackingPolicyApprovalStepDAO.build(
        {
            designatedReviewer: approvalStep.designatedReviewer ?? null,
            instanceId: approvalStep.instanceId,
            policyId: approvalStep.policyId,
            position: approvalStep.position,
        },
        { isNewRecord: !isAlreadyCreated },
    );
    if (isAlreadyCreated) {
        dao.id = approvalStep.id;
        dao.createdAt = approvalStep.createdAt;
        dao.updatedAt = approvalStep.updatedAt;
        dao.deletedAt = approvalStep.deletedAt;
    }
    return dao;
};
