'use strict';

async function publicityGet (ctx) {
    try {
        const models = ctx.fs.dc.models;
        const { enable } = ctx.query;
        let findOption = {
            where: {},
            order: [['id', 'DESC']]
        }
        if (enable) {
            findOption.where.enable = true
        }

        const roadRes = await models.Publicity.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 publicityEdit (ctx) {
    try {
        const models = ctx.fs.dc.models;
        const data = ctx.request.body;

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

        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 publicityDel (ctx) {
    try {
        const models = ctx.fs.dc.models;
        const { publicityId } = ctx.params;

        await models.Publicity.destroy({
            where: {
                id: publicityId
            }
        })

        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 = {
    publicityGet, publicityEdit, publicityDel,
};