'use strict';

async function bridgeGet (ctx) {
    try {
        const models = ctx.fs.dc.models;
        const { bridgeName } = ctx.query;

        let findOption = {
            where: {
                
            },
            order: [['id', 'DESC']]
        }
        if (bridgeName) {
            findOption.where.bridgeName = {
                $like: `%${bridgeName}%`
            }
        }

        const roadRes = await models.Bridge.findAll(findOption)

        ctx.status = 200;
        ctx.body = roadRes
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            message: typeof error == 'string' ? error : undefined
        }
    }
}

async function bridgeEdit (ctx) {
    try {
        const models = ctx.fs.dc.models;
        const data = ctx.request.body;

        if (!data.bridgeId) {
            await models.Bridge.create(data)
        } else {
            await models.Bridge.update(
                data, {
                where: {
                    id: data.bridgeId
                }
            })
        }

        ctx.status = 204
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            message: typeof error == 'string' ? error : undefined
        }
    }
}

async function bridgeDel (ctx) {
    try {
        const models = ctx.fs.dc.models;
        const { bridgeId } = ctx.params;

        await models.Bridge.destroy({
            where: {
                id: bridgeId
            }
        })

        ctx.status = 204
    } catch (error) {
        ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
        ctx.status = 400;
        ctx.body = {
            message: typeof error == 'string' ? error : undefined
        }
    }
}

module.exports = {
    bridgeGet, bridgeEdit, bridgeDel,
};