package main

import (
	"fmt"
	"os"
	"path/filepath"

	"gitlab.com/mbugroup/lti-api.git/internal/cache"
	"gitlab.com/mbugroup/lti-api.git/internal/config"
	"gitlab.com/mbugroup/lti-api.git/internal/readapi"
	"gitlab.com/mbugroup/lti-api.git/internal/route"

	"github.com/gofiber/fiber/v2"
	"github.com/redis/go-redis/v9"
)

func main() {
	root, err := findRepoRoot()
	if err != nil {
		panic(err)
	}

	readapi.PrimeBuildConfig()
	cache.SetRedis(redis.NewClient(&redis.Options{Addr: "127.0.0.1:6379"}))
	app := fiber.New(config.FiberConfig())
	app.Get("/healthz", func(c *fiber.Ctx) error {
		return c.JSON(fiber.Map{"status": "ok", "service": "api", "version": config.Version})
	})
	app.Get("/readyz", func(c *fiber.Ctx) error {
		return c.JSON(fiber.Map{"status": "ok", "db": "up", "redis": "up"})
	})
	route.Routes(app, nil)

	artifacts, err := readapi.BuildArtifactsFromApp(app)
	if err != nil {
		panic(err)
	}

	files := map[string][]byte{
		filepath.Join(root, "docs", "openapi", "read-api.json"):             artifacts.OpenAPIJSON,
		filepath.Join(root, "docs", "openapi", "read-api.yaml"):             artifacts.OpenAPIYAML,
		filepath.Join(root, "docs", "postman", "read-api.collection.json"):  artifacts.PostmanCollectionJSON,
		filepath.Join(root, "docs", "postman", "read-api.environment.json"): artifacts.PostmanEnvironmentJSON,
	}

	for path, body := range files {
		if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
			panic(err)
		}
		if err := os.WriteFile(path, body, 0o644); err != nil {
			panic(err)
		}
		fmt.Printf("wrote %s\n", path)
	}
}

func findRepoRoot() (string, error) {
	wd, err := os.Getwd()
	if err != nil {
		return "", err
	}

	current := wd
	for {
		if _, err := os.Stat(filepath.Join(current, "go.mod")); err == nil {
			return current, nil
		}
		parent := filepath.Dir(current)
		if parent == current {
			return "", fmt.Errorf("go.mod not found from %s", wd)
		}
		current = parent
	}
}
