import { InvalidIdError } from "../../controller/customErrors";
import { Category } from "../category.model";

export class CategoriesDAO {
    
    async getCategories() : Promise<Array<Category>> {
        const categories = await Category.findAll();
        return categories;
    }

    async getCategory(categoryId: number) : Promise<Category> {
        const category : Category|null = await Category.findOne({where: {id: categoryId}});
        if (category != null) {
            return category;
        } else {
            throw new InvalidIdError('No category with given categoryId.');
        }
    }

    async addCategory(category: Category) : Promise<Category> {
        //Going through values individually, instead of category.dataValues due to contraint conflicts (e.g. if category has non-unique id property).
        return await Category.create({
            title: category.title,
            color: category.color
        });
    }

    async updateCategory(categoryId: number, category: Category) : Promise<void> {
        const updatedCategories = await Category.update(
            {
                title: category.title,
                color: category.color
            },
            {where: {id: categoryId}}
        );
        if (updatedCategories[0] == 0) {
            throw new InvalidIdError('No category with given categoryId.')
        }

    }

    async deleteCategory(categoryId: number) : Promise<void> {
        const deletedCategories = await Category.destroy({where: {id: categoryId}});
        if (deletedCategories == 0) {
            throw new InvalidIdError('No category with given categoryId.');
        }
    }

}