package handler

import (
	"context"
	"kontor-api-fiber/pkg/schema"
	"log"

	"github.com/gofiber/fiber/v2"
	"github.com/uptrace/bun"
)

func SetupComicRoutes(api fiber.Router) {
	comics := api.Group("/comics")
	comics.Get("/comics", GetAllComics)
	comics.Get("/publishers", GetAllPublishers)
	comics.Get("/comicworks", GetAllComicWorks)
}

func GetAllComics(c *fiber.Ctx) error {
	var comics []schema.Comic
	var err error
	var db *bun.DB
	ctx := context.Background()

	db, err = schema.GetDatabase()
	if err != nil {
		log.Fatal(err)
	}

	err = db.NewSelect().Model(&comics).Relation("Publisher").Scan(ctx)
	if err != nil {
		log.Fatal(err)
		return fiber.NewError(fiber.StatusInternalServerError)
	}

	return c.JSON(comics)
}

func GetAllPublishers(c *fiber.Ctx) error {
	var publishers []schema.Publisher
	var err error
	var db *bun.DB
	ctx := context.Background()

	db, err = schema.GetDatabase()
	if err != nil {
		log.Fatal(err)
	}

	err = db.NewSelect().Model(&publishers).Relation("ParentPublisher").Scan(ctx)
	if err != nil {
		log.Fatal(err)
		return fiber.NewError(fiber.StatusInternalServerError)
	}

	return c.JSON(publishers)
}

func GetAllComicWorks(c *fiber.Ctx) error {
	var comic_works []schema.ComicWork
	var err error
	var db *bun.DB
	ctx := context.Background()

	db, err = schema.GetDatabase()
	if err != nil {
		log.Fatal(err)
	}

	err = db.NewSelect().Model(&comic_works).Relation("Comic").Relation("Artist").Relation("WorkType").Scan(ctx)
	if err != nil {
		log.Fatal(err)
		return fiber.NewError(fiber.StatusInternalServerError)
	}

	return c.JSON(comic_works)
}
