package service

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

	"3588AdminBackend/internal/config"
)

type Template struct {
	Name   string      `json:"name"`
	Schema interface{} `json:"schema"`
	Body   interface{} `json:"body"`
}

type TemplateService struct {
	cfg *config.Config
}

func NewTemplateService(cfg *config.Config) *TemplateService {
	return &TemplateService{cfg: cfg}
}

func (s *TemplateService) ListTemplates() ([]Template, error) {
	files, err := os.ReadDir("templates")
	if err != nil {
		return nil, err
	}

	var list []Template
	for _, f := range files {
		if !f.IsDir() && filepath.Ext(f.Name()) == ".json" {
			data, err := os.ReadFile(filepath.Join("templates", f.Name()))
			if err != nil {
				continue
			}
			var t Template
			if err := json.Unmarshal(data, &t); err == nil {
				if t.Name == "" {
					t.Name = f.Name() // Fallback
				}
				list = append(list, t)
			}
		}
	}
	return list, nil
}

func (s *TemplateService) GetTemplate(name string) (*Template, error) {
	path := filepath.Join("templates", name+".json")
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}
	var t Template
	if err := json.Unmarshal(data, &t); err != nil {
		return nil, err
	}
	return &t, nil
}
