package main

import (
	"context"
	"log"
	"net/http"
	"time"

	"royal-pop-backend/internal/config"
	"royal-pop-backend/internal/database"
	"royal-pop-backend/internal/httpx"
	"royal-pop-backend/internal/inventory"
	"royal-pop-backend/internal/mailer"
	"royal-pop-backend/internal/orders"
)

func main() {
	cfg := config.Load()
	db, err := database.NewPostgres(cfg.DatabaseURL)
	if err != nil {
		log.Fatalf("connect postgres: %v", err)
	}
	defer db.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	if err := db.EnsureSchema(ctx); err != nil {
		log.Fatalf("ensure postgres schema: %v", err)
	}

	handler := httpx.NewRouter(httpx.RouterConfig{
		Config: cfg,
		DB:     db,
		Orders: orders.NewStore(db),
		Stock:  inventory.NewStore(db),
		Mailer: mailer.NewResendMailer(cfg),
	})

	log.Printf("royal-pop api listening on %s", cfg.Address())
	if err := http.ListenAndServe(cfg.Address(), handler); err != nil {
		log.Fatal(err)
	}
}
