import express from 'express';
import { set } from 'lodash';
import { getRepository } from 'typeorm';
import { PropertyEntity } from '../../../../entities/property.entity';
import { propertySystem } from '../../../../features/properties';

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

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

    const freshProperty = await getRepository(PropertyEntity).findOne(Number(req.body.propertyId));
    if (!freshProperty) {
        return res.sendStatus(404);
    }

    const property = propertySystem.properties.find((prop) => prop.id === Number(req.body.propertyId));
    if (!property) {
        return res.sendStatus(500);
    }

    const parameter = req.body.parameter as keyof PropertyEntity;

    set(property, parameter, freshProperty[parameter]);

    if (parameter === 'extra_furniture_slots') {
        await propertySystem.refreshFurnitureSlots(property);
    }

    return res.sendStatus(200);
}
