import {Response, Router} from "express";
import {AuthenticatedRequest} from "../middlewares/authenticate";
import {canEditGuild} from "../../controller/discord";
import {getChannelById, listChannels} from "../../controller/channel";
import {validateSchema} from "../../util/validate";
import {patchChannel} from "../validations/channelValidation";

const app = Router();

const checkChannel = async (req: AuthenticatedRequest, res: Response) => {
    if (!req.params.channelId) {
        res.status(400).json({message: "Missing channelId parameter"});
        return;
    }

    const channel = await getChannelById(req.params.channelId as string);

    if (!channel) {
        res.status(404).json({message: "Channel not found"});
        return;
    }

    if (!await canEditGuild(req.user.refreshDate!, req.user.refreshToken, req.user.accessToken, channel.guildId.toString())) {
        res.status(403).json({message: "You are not allowed to edit this guild"});
        return;
    }

    return channel;
}

app.get("/", async (req: AuthenticatedRequest, res: Response) => {
    if (!req.query.guildId)
        return res.status(400).json({message: "Missing guildId query parameter"});
    if (!await canEditGuild(req.user.refreshDate!, req.user.refreshToken, req.user.accessToken, req.query.guildId as string))
        return res.status(403).json({message: "You are not allowed to edit this guild"});

    res.json((await listChannels(req.query.guildId as string)).map(channel => ({
        ...channel.dataValues,
        id: undefined, webhookToken: undefined, guildId: undefined
    })));
});

app.delete("/:channelId", async (req: AuthenticatedRequest, res: Response) => {
    const channel = await checkChannel(req, res);
    if (!channel) return;

    await channel.destroy();

    res.json({message: "Channel deleted"});
});

app.patch("/:channelId", async (req: AuthenticatedRequest, res: Response) => {
    let channel = await checkChannel(req, res);
    if (!channel) return;

    const validationError = validateSchema(patchChannel, req.body);
    if (validationError) return res.status(400).json({message: validationError});

    if (Object.keys(req.body).length === 0)
        return res.status(400).json({message: "Please select at least one field to update"});

    await channel.update(req.body);

    res.json({message: "Channel updated"});
});

module.exports = app;