import express from 'express';
import { companySystem } from '../../../../features/company';
import { ChatSystem } from '../../../../features/chat';
import { PlayerSystem } from '../../../../features/player';
import { getRepository } from 'typeorm';
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 PruneEmployees(req: express.Request, res: express.Response) {
    const by = req.body.by;
    const companyId = Number(req.body.companyId);
    const reason = req.body.reason;

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

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

    await getRepository(CharacterCompanyPositionEntity).delete({
        company_id: company.id,
    });

    company.employees.forEach((employee) => {
        const employeePed = PlayerSystem.GetPlayerFromCharacterId(employee.id);
        if (employeePed) {
            employeePed.character.companies = employeePed.character.companies.filter((c) => c.id !== companyId);
            employeePed.character.companyPositions = employeePed.character.companyPositions.filter((p) => p.company_id !== companyId);
            permissionSystem.loadPlayerPermissions(employeePed, true);
            ChatSystem.ImportantOOCNotice(employeePed, `Employees of ${company.name} were pruned by ${by}, you were removed from the company.`);
        } else {
            acknowledgeSystem
                .createMessage({
                    character_id: employee.id,
                    author: 'System',
                    content: `Employees of ${company.name} were pruned by ${by}, you were removed from the company.`,
                })
                .then();
        }
    });

    company.employees = [];

    ChatSystem.AdminWarn(`<Web> ${by} pruned all members of company ${company.id}, ${company.name}, reason: ${reason}`);

    res.sendStatus(200);
}
