package handler

import (
	"context"
	"fmt"
	"kontor-api-echo/pkg/schema"
	"log"
	"net/http"

	"github.com/labstack/echo/v4"
	"github.com/uptrace/bun"
)

func SetupComicRoutes(api *echo.Group) {
	comics := api.Group("/comics")
	comics.GET("/comics", GetAllComics)
	comics.GET("/publishers", GetAllPublishers)
	comics.GET("/comicworks", GetAllComicWorks)
}

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

	fmt.Printf("REQUEST: uri: %v, status: %v\n", c.Request().URL, c.Response().Status)
	log.Printf("REQUEST: uri: %v, status: %v\n", c.Request().URL, c.Response().Status)
	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 echo.ErrInternalServerError
	}

	return c.JSON(http.StatusOK, comics)
}

func GetAllPublishers(c echo.Context) 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 echo.ErrInternalServerError
	}

	return c.JSON(http.StatusOK, publishers)
}

func GetAllComicWorks(c echo.Context) 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 echo.ErrInternalServerError
	}

	return c.JSON(http.StatusOK, comic_works)
}
