import express from 'express';
import { permissionSystem } from '../../../../features/permission';
import { groupSystem } from '../../../../features/groups';
import { propertySystem } from '../../../../features/properties';
import { getRepository } from 'typeorm';
import { CharacterEntity } from '../../../../entities/character.entity';
import { PlayerSystem } from '../../../../features/player';
import { ChatColors } from '../../../../const/chat-colors';

export async function GroupMemberChanged(req: express.Request, res: express.Response): Promise<express.Response<any, Record<string, any>>> {
    if (!req.params.accountId) {
        res.status(400).send('Missing parameter');
    }

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

    const accountId = Number(req.params.accountId);
    for (const player of mp.players.toArray()) {
        if (player.account?.id === accountId) {
            await groupSystem.refreshPlayerGroups(player);
            await permissionSystem.loadPlayerPermissions(player, true);
            const isPremium = PlayerSystem.IsPremium(player);
            if (!isPremium && player.getVariable('premium')) {
                player.outputChatBox(ChatColors.orange + `Your SW-RP Premium expired.`);
            } else if (isPremium && !player.getVariable('premium')) {
                player.outputChatBox(ChatColors.orange + `SW-RP Premium has been activated on your account.`);
            }
            player.setVariable('premium', PlayerSystem.IsPremium(player));
        }
    }

    const characters = await getRepository(CharacterEntity).find({
        where: {
            account_id: accountId,
        },
    });

    for (const character of characters) {
        for (const property of propertySystem.properties) {
            if (property.character_id && property.character_id === character.id) {
                await propertySystem.refreshFurnitureSlots(property);
            }
        }
    }

    return res.sendStatus(200);
}
