package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"text/template"
)

type TemplateData struct {
	PackageName  string
	VariableName string
	StructName   string
}

func main() {
	table := flag.String("table", "", "enter the required data table")
	flag.Parse()

	tableName := *table
	if tableName == "" {
		log.Fatal("table cannot be empty, please provide a valid table name.")
	}

	// 获取当前工作目录
	wd, err := os.Getwd()
	if err != nil {
		log.Fatalf("Error getting working directory:%s", err.Error())
	}

	// 模板文件路径
	tmplPath := fmt.Sprintf("%s/cmd/handlergen/handler_template.go.tpl", wd)
	tmpl, err := template.ParseFiles(tmplPath)
	if err != nil {
		log.Fatal(err)
	}

	log.Printf("Template file parsed: %s", tmplPath)

	// 替换的变量
	data := TemplateData{
		PackageName:  tableName,
		VariableName: tableName,
		StructName:   toCamelCase(tableName),
	}

	// 生成文件的目录和文件名
	outputDir := fmt.Sprintf("%s/internal/api/%s", wd, tableName)
	outputFile := filepath.Join(outputDir, fmt.Sprintf("%s.gen.go", tableName))

	// 创建目录
	err = os.MkdirAll(outputDir, os.ModePerm)
	if err != nil {
		log.Fatal(err)
	}

	// 创建文件
	file, err := os.Create(outputFile)
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	log.Printf("File created: %s", outputFile)

	// 执行模板并生成文件
	err = tmpl.Execute(file, data)
	if err != nil {
		log.Fatal(err)
	}

	log.Println("Template execution completed successfully.")
}

// 将字符串转为驼峰式命名
func toCamelCase(s string) string {
	// 用下划线分割字符串
	parts := strings.Split(s, "_")

	// 对每个部分首字母大写
	for i := 0; i < len(parts); i++ {
		parts[i] = strings.Title(parts[i])
	}

	// 拼接所有部分
	return strings.Join(parts, "")
}
