package drizzle

import (
	"bytes"
	"text/template"
)

// schemaTemplate defines the template for generating Drizzle schemas
const schemaTemplate = `// Code generated by relspecgo. DO NOT EDIT.
{{range .Imports}}{{.}}
{{end}}
{{if .Enums}}
// Enums
{{range .Enums}}export const {{.VarName}} = pgEnum('{{.Name}}', [{{.ValuesStr}}]);
export type {{.Name}} = {{.TypeUnion}};
{{end}}
{{end}}
{{range .Tables}}// Table: {{.TableName}}{{if .Comment}} - {{.Comment}}{{end}}
export interface {{.TypeName}} {
{{- range $i, $col := .Columns}}
  {{$col.FieldName}}: {{$col.TypeScriptType}};{{if $col.Comment}} // {{$col.Comment}}{{end}}
{{- end}}
}

export const {{.Name}} = pgTable('{{.TableName}}', {
{{- range $i, $col := .Columns}}
  {{$col.FieldName}}: {{$col.DrizzleChain}},{{if $col.Comment}} // {{$col.Comment}}{{end}}
{{- end}}
}{{if .Indexes}}{{if .IndexColumnFields}}, ({ {{range $i, $field := .IndexColumnFields}}{{if $i}}, {{end}}{{$field}}{{end}} }) => [{{else}}, (table) => [{{end}}
{{- range $i, $idx := .Indexes}}
  {{$idx.Definition}},
{{- end}}
]{{end}});

export type New{{.TypeName}} = typeof {{.Name}}.$inferInsert;
{{end}}`

// Templates holds the parsed templates
type Templates struct {
	schemaTmpl *template.Template
}

// NewTemplates creates and parses the templates
func NewTemplates() (*Templates, error) {
	schemaTmpl, err := template.New("schema").Parse(schemaTemplate)
	if err != nil {
		return nil, err
	}

	return &Templates{
		schemaTmpl: schemaTmpl,
	}, nil
}

// GenerateCode executes the template with the given data
func (t *Templates) GenerateCode(data *TemplateData) (string, error) {
	var buf bytes.Buffer
	err := t.schemaTmpl.Execute(&buf, data)
	if err != nil {
		return "", err
	}

	return buf.String(), nil
}
