import express from 'express';
import { getRepository } from 'typeorm';
import { CharacterEntity } from '../../../../entities/character.entity';
import { PlayerSystem } from '../../../../features/player';
import { MoneySystem } from '../../../../features/money';
import { MoneyChangeReasons } from '../../../../features/money/money_change_reasons';

export async function CharacterSpawnMoney(req: express.Request, res: express.Response) {
    const character = req.params.characterId;

    const by = req.body.byName;

    if (!character) {
        return res.status(400).send('Missing key parameter');
    }

    if (!by) {
        return res.status(400).send(`Missing issuer parameter`);
    }

    const characterId = Number(character);

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

    const characterEntity = await getRepository(CharacterEntity).findOne(characterId);

    if (!characterEntity) {
        return res.status(400).send('Invalid character entity for target.');
    }

    if (!req.body.amount) {
        return res.status(400).send(`Missing value parameter`);
    }

    const amount = Number(req.body.amount);

    if (amount <= 0) {
        return res.status(400).send(`Invalid value parameter`);
    }

    const isInGame = PlayerSystem.GetPlayerFromCharacterId(characterEntity.id);
    if (isInGame) {
        return res.status(400).send(`Target character is now in-game, re-try issuing..`);
    }

    const before = characterEntity.cash;

    await getRepository(CharacterEntity).update(characterEntity.id, {
        cash: before + amount,
    });

    await MoneySystem.LogMoneyChange(
        characterEntity.id,
        characterEntity.account_id,
        amount,
        before,
        before + amount,
        MoneyChangeReasons.UCP_REFUND,
        `${by} refunded ${characterEntity.name} $${MoneySystem.FormatMoney(amount)}`,
    );

    res.sendStatus(200);
}
