import { validateSessionUser } from "../../helpers/check";
import {
    IFavouritesManager,
    IFavouritesAdapter,
    CreateFavouriteParams,
    DeleteFavouriteParams,
    IFavourite,
    PaginateFavouritesParams,
    PaginateFavouritesResults,
} from "./Favourites.interface";

export class FavouritesManager implements IFavouritesManager {
    favourites: IFavouritesAdapter;

    constructor(favouritesAdapter: IFavouritesAdapter) {
        this.favourites = favouritesAdapter;
    }

    async createFavourite(data: CreateFavouriteParams): Promise<IFavourite> {
        await validateSessionUser({
            sessionUser: data.sessionUser,
        });

        const favourite = await this.favourites.create(data);

        if (!favourite) {
            throw new Error("Ha ocurrido un error al crear el favorito");
        }

        return favourite;
    }

    async deleteFavourite(data: DeleteFavouriteParams): Promise<void> {
        await validateSessionUser({
            sessionUser: data.sessionUser,
        });

        const favourite = await this.favourites.findOne({ id: data.id });

        if (!favourite) {
            throw new Error("El favorito que intenta eliminar no existe");
        }

        await this.favourites.delete(data);
    }

    async paginate(data: PaginateFavouritesParams): Promise<PaginateFavouritesResults> {
        return this.favourites.paginate(data);
    }
}
