package main

import (
	pb "github.com/go-kratos/kratos/v2/api/kratos/api"

	"google.golang.org/protobuf/compiler/protogen"
	"google.golang.org/protobuf/proto"
)

const (
	errorsPackage = protogen.GoImportPath("github.com/go-kratos/kratos/v2/errors")
)

// generateFile generates a _http.pb.go file containing kratos errors definitions.
func generateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {
	if len(file.Enums) == 0 {
		return nil
	}
	filename := file.GeneratedFilenamePrefix + "_errors.pb.go"
	g := gen.NewGeneratedFile(filename, file.GoImportPath)
	g.P("// Code generated by protoc-gen-go-errors. DO NOT EDIT.")
	g.P()
	g.P("package ", file.GoPackageName)
	g.P()
	generateFileContent(gen, file, g)
	return g
}

// generateFileContent generates the kratos errors definitions, excluding the package statement.
func generateFileContent(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile) {
	if len(file.Enums) == 0 {
		return
	}

	g.P("// This is a compile-time assertion to ensure that this generated file")
	g.P("// is compatible with the kratos package it is being compiled against.")
	g.P("const _ = ", errorsPackage.Ident("SupportPackageIsVersion1"))
	g.P()
	for _, enum := range file.Enums {
		genErrorsReason(gen, file, g, enum)
	}
}

func genErrorsReason(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, enum *protogen.Enum) {
	err := proto.GetExtension(enum.Desc.Options(), pb.E_Errors)
	if ok := err.(bool); !ok {
		return
	}
	var ew errorWrapper
	for _, v := range enum.Values {
		err := &errorInfo{
			Name:  string(enum.Desc.Name()),
			Value: string(v.Desc.Name()),
		}
		ew.Errors = append(ew.Errors, err)
	}
	g.P(ew.execute())
}