import { Request, Response, NextFunction } from "express";
import { VISIBILITY } from "../types/common.types";
import Source from "../models/source.model";
import createHttpError from "http-errors";

export default class SourceController {
    static async create(request: Request, response: Response, next: NextFunction) {
        try {
            const channel_id = request.body.channel_id;
            const source = request.body.source;
            const rank = Number(request?.body?.rank || 0);
            const status: VISIBILITY = request.body?.status === 'HIDDEN' ? VISIBILITY.HIDDEN : VISIBILITY.VISIBLE;
            const data = await Source.create({
                channel_id: Number(channel_id),
                source: String(source || ''),
                rank: rank,
                status: status
            });
            response.status(203).json(data?.dataValues);
        } catch (error) {
            next(error);
        }
    }
    static async getAll(request: Request, response: Response, next: NextFunction) {
        try {
            const data = await Source.findAll();
            response.status(203).json(data);
        } catch (error) {
            next(error);
        }
    }
    static async getById(request: Request, response: Response, next: NextFunction) {
        try {
            const data = await Source.findByPk(request.params.id);
            if(!data?.dataValues) throw createHttpError.NotFound("Source not found!");
            response.status(203).json(data);
        } catch (error) {
            next(error);
        }
    }
    static async updateById(request: Request, response: Response, next: NextFunction) {
        try {
            const id = request.params.id;
            const data = request.body || {};
            const source = await Source.findByPk(id);
            if (data?.id) delete data?.id;
            if (!source?.dataValues) throw createHttpError.NotFound("Source Not Found.");
            else await source.update(data);
            response.status(203).json({
                message: 'Source updated.'
            });
        } catch (error) {
            next(error);
        }
    }
    static async deleteById(request: Request, response: Response, next: NextFunction) {
        try {
            const id = request.params.id;
            await Source.destroy({
                where: { id: id }
            });
            response.status(203).json({
                message: 'Source removed.'
            });
        } catch (error) {
            next(error);
        }
    }
}