package server

import (
	"fmt"
	"net/http"

	"git.ctrlz.es/mgdelacroix/rmsn/model"
	"git.ctrlz.es/mgdelacroix/rmsn/services/store"
	"git.ctrlz.es/mgdelacroix/rmsn/web"
)

type Server struct {
	Config *model.Config

	Store     *store.Store
	WebServer *http.Server
}

func NewServer(config *model.Config) (*Server, error) {
	if err := config.IsValid(); err != nil {
		return nil, fmt.Errorf("config is not valid: %w", err)
	}

	webserver, err := web.NewWebServer(*config.Port)
	if err != nil {
		return nil, fmt.Errorf("cannot create webserver: %w", err)
	}

	store, err := store.NewStore(*config.DatabasePath)
	if err != nil {
		return nil, fmt.Errorf("cannot create store: %w", err)
	}

	return &Server{
		Config:    config,
		WebServer: webserver,
		Store:     store,
	}, err
}

func NewServerWithConfigPath(path string) (*Server, error) {
	config, err := model.ReadConfig(path)
	if err != nil {
		return nil, fmt.Errorf("cannot read config from path %q: %w", path, err)
	}

	return NewServer(config)
}

func (s *Server) Start() error {
	// ToDo: start webserver here

	return nil
}

func (s *Server) Close() error {
	// ToDo: stop webserver
	// ToDo: close store

	return nil
}
