package config

//go:generate go run ../../cmd/cspgenerator/

import (
	"fmt"
	"os"
	"reflect"

	"github.com/crewjam/csp"
	"github.com/fatih/structtag"
	"gitlab.com/tozd/go/errors"
)

func GenerateCSP() error {
	t := reflect.TypeFor[csp.Header]()
	file, err := os.OpenFile("./csp.go", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0)
	if err != nil {

		return errors.WithMessage(err, "could not write to output")
	}
	defer file.Close()

	_, err = fmt.Fprintf(file, `package config

// Code generated  DO NOT EDIT.

import (
	"github.com/crewjam/csp"
)

`)
	if err != nil {

		return errors.WithMessage(err, "could not write to output")
	}

	_, err = fmt.Fprintf(file, "type CSP struct {\n")
	if err != nil {
		return errors.WithMessage(err, "could not write to output")
	}

	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)
		var t reflect.Type
		t = field.Type
		tags, err := structtag.Parse(string(field.Tag))
		if err != nil {
			return errors.WithMessage(err, "could not write to output")
		}
		cspTag, err := tags.Get("csp")
		if err != nil {
			return errors.WithMessage(err, "could not get csp tag")
		}
		err = tags.Set(&structtag.Tag{
			Key:  "toml",
			Name: cspTag.Name,
		})
		if err != nil {
			return errors.WithMessage(err, "could not set toml tag")
		}

		_, err = fmt.Fprintf(file, "\t%-23s %-28s `%s`\n", field.Name, t, tags.String())
		if err != nil {
			return errors.WithMessage(err, "could not write to output")
		}
	}
	_, err = fmt.Fprintln(file, "}")
	if err != nil {
		return errors.WithMessage(err, "could not write to output")
	}

	_, err = fmt.Fprintln(file, `
func (c *CSP) String() string {
	return csp.Header(*c).String()
}`)
	if err != nil {
		return errors.WithMessage(err, "could not write to output")
	}

	return nil
}