package main

import (
	"context"
	"log/slog"
	"os"
	"recipes/internal/config"
	"recipes/internal/lib/logger/sl"
	"recipes/internal/media_storage/minio"
	"recipes/internal/parser"
	"recipes/internal/storage/postgresql"

	prettyLogger "github.com/charmbracelet/log"
)

const (
	envLocal = "local"
	envDev   = "dev"
	envProd  = "prod"
)

func main() {
	// read config
	cfg := config.MustLoad()
	// init logger
	log := setupLogger(cfg.Env)
	// init storage
	storage, err := postgresql.New(
		context.Background(),
		cfg.Postgresql.User,
		cfg.Postgresql.Password,
		cfg.Postgresql.Address,
		cfg.Postgresql.DBName,
	)
	if err != nil {
		log.Error("failed to init storage", sl.Err(err))
		os.Exit(1)
	}
	// init media storage
	mstorage, err := minio.New(
		context.Background(),
		cfg.Minio.Address,
		cfg.Minio.User,
		cfg.Minio.Password,
	)
	if err != nil {
		log.Error("failed to init media storage", sl.Err(err))
		os.Exit(1)
	}
	// run parser
	_, err = parser.SavePage(log, 1, mstorage, storage, storage)
	if err != nil {
		log.Error("Parse failed", sl.Err(err))
		os.Exit(1)
	}
	log.Info("parsing was completed successfully")
}

func setupLogger(env string) *slog.Logger {
	var log *slog.Logger

	switch env {
	case envLocal:
		// log = slog.New(
		// 	slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}),
		// )
		handler := prettyLogger.NewWithOptions(os.Stdout, prettyLogger.Options{Level: prettyLogger.DebugLevel})
		log = slog.New(handler)
	case envDev:
		log = slog.New(
			slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}),
		)
	case envProd:
		log = slog.New(
			slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}),
		)
	}

	return log
}