import express from 'express';
import { companySystem } from '../../../../features/company';
import { PlayerSystem } from '../../../../features/player';
import { getRepository } from 'typeorm';
import { CharacterCompanyPositionEntity } from '../../../../entities/character-company-positions.entity';
import { acknowledgeSystem } from '../../../../features/player/acknowledge';
import { ChatSystem } from '../../../../features/chat';

export async function EmployeePosition(req: express.Request, res: express.Response) {
    const by = req.body.by;
    const companyId = Number(req.body.companyId);
    const characterId = Number(req.body.characterId);
    const positionId = Number(req.body.positionId);

    const company = companySystem.getCompanyById(companyId);
    if (!company) {
        return res.sendStatus(404);
    }

    const position = company.positions.find((pos) => pos.id === positionId);
    if (!position) {
        return res.sendStatus(404);
    }

    const characterPed = PlayerSystem.GetPlayerFromCharacterId(characterId);

    await getRepository(CharacterCompanyPositionEntity).update(
        {
            character_id: characterId,
            company_id: companyId,
        },
        {
            company_position_id: positionId,
        },
    );

    if (characterPed) {
        characterPed.character.companyPositions = characterPed.character.companyPositions.filter((pos) => pos.company_id !== companyId);
        characterPed.character.companyPositions.push(position);
        const companyPnt = company.employees.find((employee) => employee.id === characterId);
        if (companyPnt) {
            companyPnt.companyPositions = characterPed.character.companyPositions;
        }
        ChatSystem.ImportantOOCNotice(characterPed, `Your position in ${company.name} was updated to ${position.name} by ${by}.`);
    } else {
        acknowledgeSystem
            .createMessage({
                character_id: characterId,
                author: 'System',
                content: `Your position in ${company.name} was updated to ${position.name} by ${by}`,
            })
            .then();
    }

    res.sendStatus(200);
}
