import express from 'express';
import { getRepository } from 'typeorm';
import { InventoryEntity } from '../../../../entities/inventory.entity';
import { preloadSystem } from '../../../../core/preload';
import { ItemEntity } from '../../../../entities/item.entity';
import { LogSystem } from '../../../../core/log';
import { ItemTypeEntity } from '../../../../entities/item-type.entity';
import { CharacterEntity } from '../../../../entities/character.entity';

export async function CharacterSpawnItem(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.itemTypeId) {
        return res.status(400).send(`Missing item type parameter`);
    }

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

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

    const inventory = await getRepository(InventoryEntity).findOne({
        where: {
            game_entity_id: characterId,
            game_entity_type_id: preloadSystem.getGameEntityTypeId('character'),
        },
    });

    if (!inventory) {
        return res.status(400).send(`Target has no inventory.`);
    }

    const itemType = await getRepository(ItemTypeEntity).findOne(itemTypeId);

    if (!itemType) {
        return res.status(400).send(`Invalid item entity.`);
    }

    const result = await getRepository(ItemEntity).insert({
        amount: amount * itemType.amount_multiplier,
        type_id: itemType.id,
        inventory_id: inventory.id,
        data: itemType.default_item_data || {},
    });

    const entity = await getRepository(ItemEntity).findOne(result.raw.insertId);

    if (entity) {
        LogSystem.ItemEvent(entity, 'created', `Created by ${by}'s web refund to ${characterEntity.name}`);
    }

    res.sendStatus(200);
}
