package jobdef

import (
	"context"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"

	"scheduler-backend/internal/store/model"
	"scheduler-backend/pkg/log"
)

type JobConfigUpserter interface {
	UpsertByHandlerKey(ctx context.Context, item *model.JobConfig) error
}

type configFile struct {
	Name          string `json:"name"`
	HandlerKey    string `json:"handlerKey"`
	ScheduleType  string `json:"scheduleType"`
	ScheduleValue string `json:"scheduleValue"`
	DefaultParams string `json:"defaultParams"`
}

func SyncJobConfigs(ctx context.Context, dir string, store JobConfigUpserter, logger log.Logger) error {
	matches, err := filepath.Glob(filepath.Join(dir, "*.json"))
	if err != nil {
		return fmt.Errorf("glob job config files: %w", err)
	}
	if len(matches) == 0 {
		logger.Info("no job config files found", "dir", dir)
		return nil
	}

	for _, path := range matches {
		data, err := os.ReadFile(path)
		if err != nil {
			return fmt.Errorf("read %s: %w", path, err)
		}
		var cfg configFile
		if err := json.Unmarshal(data, &cfg); err != nil {
			return fmt.Errorf("parse %s: %w", path, err)
		}
		if cfg.HandlerKey == "" {
			return fmt.Errorf("%s: handlerKey is required", path)
		}

		item := &model.JobConfig{
			Name:          cfg.Name,
			HandlerKey:    cfg.HandlerKey,
			ScheduleType:  cfg.ScheduleType,
			ScheduleValue: cfg.ScheduleValue,
			DefaultParams: cfg.DefaultParams,
		}
		if err := store.UpsertByHandlerKey(ctx, item); err != nil {
			return fmt.Errorf("upsert %s: %w", cfg.HandlerKey, err)
		}
		logger.Info("synced job config", "handlerKey", cfg.HandlerKey, "name", cfg.Name, "file", filepath.Base(path))
	}
	return nil
}
