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 { CharacterEntity } from '../../../../entities/character.entity';

export async function CharacterDeleteItem(req: express.Request, res: express.Response) {
    const character = req.params.characterId;
    const itemId = req.body?.itemId;
    const by = req.body?.byName;

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

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

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

    const characterId = Number(character);
    const parsedItemId = Number(itemId);

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

    if (!parsedItemId || isNaN(parsedItemId)) {
        return res.status(500).send('Unable to parse itemId parameter');
    }

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

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

    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 item = await getRepository(ItemEntity).findOne({
        where: {
            id: parsedItemId,
            inventory_id: inventory.id,
        },
    });

    if (!item) {
        return res.status(404).send('Item not found in this character inventory.');
    }

    const itemTypeId = item.type_id;
    const itemAmount = item.amount;

    await getRepository(ItemEntity).delete(parsedItemId);

    LogSystem.ItemEvent(item, 'deleted', `Deleted by ${by}'s web admin action from ${characterEntity.name}`);

    res.status(200).json({
        itemId: parsedItemId,
        typeId: itemTypeId,
        amount: itemAmount,
    });
}
