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

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

    const characterPed = PlayerSystem.GetPlayerFromCharacterId(characterId);
    const characterEntity = await getRepository(CharacterEntity).findOne(characterId);
    const company = companySystem.getCompanyById(companyId);
    if (!company) {
        res.sendStatus(404);
        return;
    }

    if (!characterEntity) {
        res.sendStatus(404);
        return;
    }

    await getRepository(CharacterCompanyPositionEntity).delete({
        character_id: characterId,
        company_id: companyId,
    });

    company.employees = company.employees.filter((emp) => emp.id !== characterId);
    ChatSystem.AdminWarn(`<Web> ${by} removed ${characterEntity.name} from company ${company.name}.`);

    if (!characterPed) {
        acknowledgeSystem
            .createMessage({
                author: 'System',
                character_id: characterId,
                content: `You were removed from company ${company.name} by ${by}.`,
            })
            .then();
    } else {
        characterPed.character.companies = characterPed.character.companies.filter((company) => company.id !== companyId);
        characterPed.character.companyPositions = characterPed.character.companyPositions.filter((pos) => pos.company_id !== companyId);
        ChatSystem.ImportantOOCNotice(characterPed, `${by} removed you from company ${company.name}.`);
        permissionSystem.loadPlayerPermissions(characterPed, true);
    }

    res.sendStatus(200);
}
