package http

import (
	"context"
	"database/sql"

	"quyun/v2/app/commands"
	"quyun/v2/app/errorx"
	appHttp "quyun/v2/app/http"
	"quyun/v2/app/jobs"
	"quyun/v2/app/middlewares"
	"quyun/v2/app/services"
	"quyun/v2/database"
	_ "quyun/v2/docs"
	"quyun/v2/providers/app"
	"quyun/v2/providers/http"
	"quyun/v2/providers/http/swagger"
	"quyun/v2/providers/job"
	"quyun/v2/providers/jwt"
	"quyun/v2/providers/postgres"
	"quyun/v2/providers/storage"

	"go.ipao.vip/atom"
	"go.ipao.vip/atom/container"
	"go.ipao.vip/atom/contracts"

	"github.com/gofiber/fiber/v3/middleware/favicon"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"go.uber.org/dig"
)

func defaultProviders() container.Providers {
	return commands.Default(container.Providers{
		http.DefaultProvider(),
		postgres.DefaultProvider(),
		jwt.DefaultProvider(),
		job.DefaultProvider(),
		database.DefaultProvider(),
		storage.DefaultProvider(),
	}...)
}

func Command() atom.Option {
	return atom.Command(
		atom.Name("serve"),
		atom.Short("run http server"),
		atom.RunE(Serve),
		atom.Providers(
			defaultProviders().
				WithProviders(
					appHttp.Providers(),
				).
				With(
					jobs.Provide,
					services.Provide,
					middlewares.Provide,
				),
		),
	)
}

type Service struct {
	dig.In

	App      *app.Config
	Job      *job.Job
	Http     *http.Service
	DB       *sql.DB
	Initials []contracts.Initial   `group:"initials"`
	Routes   []contracts.HttpRoute `group:"routes"`
}

func Serve(cmd *cobra.Command, args []string) error {
	return container.Container.Invoke(func(ctx context.Context, svc Service) error {
		log.SetFormatter(&log.JSONFormatter{})

		if svc.App.Mode == app.AppModeDevelopment {
			log.SetLevel(log.DebugLevel)

			svc.Http.Engine.Get("/swagger/*", swagger.HandlerDefault)
		}
		svc.Http.Engine.Use(errorx.Middleware)
		svc.Http.Engine.Use(favicon.New(favicon.Config{
			Data: []byte{},
		}))

		for _, route := range svc.Routes {
			group := svc.Http.Engine.Group(route.Path(), route.Middlewares()...).Name(route.Name())
			route.Register(group)
		}

		return svc.Http.Serve(ctx)
	})
}
