package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"VerifactuMidAPI/api"
	"VerifactuMidAPI/internal"
	_ "VerifactuMidAPI/internal/formats/dolibarr"
	_ "VerifactuMidAPI/internal/formats/native"
	"VerifactuMidAPI/internal/cert"
	"VerifactuMidAPI/internal/config"
	"VerifactuMidAPI/internal/crypto"
	"VerifactuMidAPI/verifactu"
)

func main() {
	cfg, err := config.Load("config.yml")
	if err != nil {
		log.Fatalf("loading config: %v", err)
	}

	certStorage := cert.NewStorage(cfg.Certificates.StoragePath)
	if err := certStorage.Init(); err != nil {
		log.Fatalf("initializing cert storage: %v", err)
	}

	keyPair, err := crypto.LoadOrCreateKeyPair(cfg.Crypto.KeysPath)
	if err != nil {
		log.Fatalf("loading/creating key pair: %v", err)
	}

	hashStorage := internal.NewFileLastRecordStorage("./data")
	facturaSvc := internal.NewFacturaService(hashStorage)

	envURL := verifactu.GetTestURL()
	if cfg.VeriFactu.Production {
		envURL = verifactu.GetProdURL()
		log.Println("VeriFactu: PRODUCTION environment")
	} else {
		log.Println("VeriFactu: TEST environment")
	}

	verifactuCfg := verifactu.ClientConfig{
		BaseURL: envURL,
		Timeout: 30 * time.Second,
	}

	client, err := verifactu.NewClient(verifactuCfg)
	if err != nil {
		log.Printf("warning: verifactu client initialization failed: %v", err)
	} else {
		facturaSvc.SetVerifactuClient(client)
		log.Printf("VeriFactu: Connected to %s", envURL)
	}

	handler := api.New(cfg, certStorage, keyPair, facturaSvc)

	mux := http.NewServeMux()
	handler.RegisterRoutes(mux)

	addr := fmt.Sprintf(":%d", cfg.Server.Port)
	log.Printf("Starting server on %s", addr)
	if err := http.ListenAndServe(addr, mux); err != nil {
		log.Fatalf("server error: %v", err)
	}
}

func init() {
	if _, err := os.Stat("config.yml"); os.IsNotExist(err) {
		log.Println("Warning: config.yml not found, using defaults")
	}
}
