import express from 'express';
import { factionSystem } from '../../../../features/faction';
import { PlayerSystem } from '../../../../features/player';
import { getRepository } from 'typeorm';
import { LogSystem } from '../../../../core/log';
import { CharacterEntity } from '../../../../entities/character.entity';
import { ChatSystem } from '../../../../features/chat';

export async function FactionKick(req: express.Request, res: express.Response): Promise<void> {
    if (!req.body.characterId) {
        res.status(400).send('Missing parameter');
        return;
    }

    if (!Number(req.body.characterId)) {
        res.status(500).send('Unable to parse given parameter');
        return;
    }

    const characterId = Number(req.body.characterId);
    const factionId = Number(req.body.factionId);
    const { accountName, characterRank } = req.body;
    const characterName = req.body.characterName.replace(/_/g, ' ');
    const targetName = req.body.targetName.replace(/_/g, ' ');

    const target = PlayerSystem.GetPlayerFromCharacterId(characterId);
    const faction = factionSystem.getFactionFromId(factionId);
    if (!faction) {
        res.status(500).send('Faction not found ingame');
        return;
    }

    try {
        if (target && mp.players.exists(target)) {
            LogSystem.PlayerEvent(
                target,
                'faction',
                `${characterRank} ${characterName} (${accountName}) removed ${target.character.getIcName(false)} from faction ${factionId} (via UCP).`,
            );
            LogSystem.FactionEvent(
                faction,
                'faction_uninvite',
                `${characterRank} ${characterName} (${accountName}) removed ${target.character.getIcName(false)} from the faction (via UCP).`,
            );
            await factionSystem.removeMember(target);
            ChatSystem.Notice(target, `You've been removed from ${faction.name} (via UCP).`);
        } else {
            await getRepository(CharacterEntity).update(characterId, {
                faction_id: null,
                faction_rank: null,
            });
            LogSystem.FactionEvent(faction, 'faction_uninvite', `${characterRank} ${characterName} (${accountName}) removed ${targetName} (via UCP).`);
        }
    } catch (e: any) {
        res.status(500).send(e.message);
        return;
    }

    res.status(200).send(`Removed ${target ? 'online' : 'offline'} player from faction`);
}
