package main

import (
	"fmt"
	"github.com/99designs/gqlgen/api"
	"github.com/99designs/gqlgen/codegen/config"
	"github.com/spf13/pflag"
	admin_api "gshopper.com/gshopify/admin-api"
	"os"
)

var (
	fModule = pflag.StringP("module", "m", "", "module name")
)

func init() {
	pflag.Parse()

	if fModule == nil || *fModule == "" {
		_, _ = fmt.Fprintf(os.Stderr, "specify module name; available modules are: %v\n", admin_api.AllModules)
		os.Exit(2)
	}
}

func main() {
	var modules []admin_api.Module
	if *fModule == "all" {
		modules = admin_api.AllModules
	} else {
		module := admin_api.Module(*fModule)
		if !module.IsValid() {
			_, _ = fmt.Fprintf(os.Stderr, "incorrect module has been specified; available modules are: %v\n", admin_api.AllModules)
			os.Exit(2)
		}

		modules = append(modules, module)
	}

	for _, module := range modules {
		if err := generate(module); err != nil {
			_, _ = fmt.Fprintf(os.Stderr, err.Error())
			os.Exit(2)
		}
	}

	os.Exit(0)
}

func generate(m admin_api.Module) error {
	schema := fmt.Sprintf("subgraph/%s.tpl", m)
	if stat, err := os.Stat(schema); err != nil || stat.Size() < 1 {
		return fmt.Errorf("illegal module schema definition")
	}

	cfg := makeConfig(m)
	if err := config.CompleteConfig(cfg); err != nil {
		return err
	}

	if err := api.Generate(cfg); err != nil {
		return err
	}

	return nil
}

func makeConfig(m admin_api.Module) *config.Config {
	cfg := config.DefaultConfig()

	// Federation
	cfg.Federation = config.PackageConfig{
		Filename: fmt.Sprintf("graph/%s/generated/federation.go", m),
		Version:  2,
	}

	// Exec
	cfg.Exec = config.ExecConfig{
		Filename: fmt.Sprintf("graph/%s/generated/generated.go", m),
	}

	// Model
	cfg.Model = config.PackageConfig{
		Filename: fmt.Sprintf("graph/%s/generated/models.go", m),
	}

	// Resolver
	cfg.Resolver = config.ResolverConfig{
		Layout:  config.LayoutFollowSchema,
		DirName: fmt.Sprintf("graph/%s", m),
	}

	// SchemaFilename
	cfg.SchemaFilename = config.StringList{
		fmt.Sprintf("subgraph/%s.tpl", m), "ext/*.graphql"}

	return cfg
}
