package main

import (
	"fmt"
	"strings"
	"time"
)

func (d *Descriptor) genNewFakeAPI(sb *strings.Builder) {
	fmt.Fprintf(sb, "type %s struct {\n", d.FakeAPIStructName())
	if d.RequiresLogin {
		fmt.Fprintf(sb, "\tWithResult %s\n", d.CallerInterfaceName())
	}
	fmt.Fprint(sb, "\tErr error\n")
	fmt.Fprintf(sb, "\tResponse %s\n", d.ResponseTypeName())
	fmt.Fprint(sb, "\tCountCall *atomicx.Int64\n")
	fmt.Fprint(sb, "}\n\n")

	fmt.Fprintf(sb, "func (fapi *%s) Call(ctx context.Context, req %s) (%s, error) {\n",
		d.FakeAPIStructName(), d.RequestTypeName(), d.ResponseTypeName())
	fmt.Fprint(sb, "\tif fapi.CountCall != nil {\n")
	fmt.Fprint(sb, "\t\tfapi.CountCall.Add(1)\n")
	fmt.Fprint(sb, "\t}\n")
	fmt.Fprint(sb, "\treturn fapi.Response, fapi.Err\n")
	fmt.Fprint(sb, "}\n\n")

	if d.RequiresLogin {
		fmt.Fprintf(sb, "func (fapi *%s) WithToken(token string) %s {\n",
			d.FakeAPIStructName(), d.CallerInterfaceName())
		fmt.Fprint(sb, "\treturn fapi.WithResult\n")
		fmt.Fprint(sb, "}\n\n")
	}

	fmt.Fprint(sb, "var (\n")
	fmt.Fprintf(sb, "\t_ %s = &%s{}\n", d.CallerInterfaceName(),
		d.FakeAPIStructName())
	if d.RequiresLogin {
		fmt.Fprintf(sb, "\t_ %s = &%s{}\n", d.ClonerInterfaceName(),
			d.FakeAPIStructName())
	}
	fmt.Fprint(sb, ")\n\n")
}

// GenFakeAPITestGo generates fakeapi_test.go.
func GenFakeAPITestGo(file string) {
	var sb strings.Builder
	fmt.Fprint(&sb, "// Code generated by go generate; DO NOT EDIT.\n")
	fmt.Fprintf(&sb, "// %s\n\n", time.Now())
	fmt.Fprint(&sb, "package ooapi\n\n")
	fmt.Fprintf(&sb, "//go:generate go run ./internal/generator -file %s\n\n", file)
	fmt.Fprint(&sb, "import (\n")
	fmt.Fprint(&sb, "\t\"context\"\n")
	fmt.Fprint(&sb, "\n")
	fmt.Fprint(&sb, "\t\"github.com/ooni/probe-cli/v3/internal/atomicx\"\n")
	fmt.Fprint(&sb, "\t\"github.com/ooni/probe-cli/v3/internal/ooapi/apimodel\"\n")
	fmt.Fprint(&sb, ")\n")
	for _, desc := range Descriptors {
		desc.genNewFakeAPI(&sb)
	}
	writefile(file, &sb)
}
