package http

import (
	"context"
	"errors"
	"golang.source-fellows.com/pattern/adapter/internal/model"
)

// To install the tooling run the following command:
//	go install github.com/deepmap/oapi-codegen/v2/cmd/oapi-codegen@latest
//
//go:generate oapi-codegen -package http -generate=types,client -o contractStore_generated.go ./openapi.yaml

type ContractStoreAdapter struct{}

func NewContractStore() *ContractStoreAdapter {
	return &ContractStoreAdapter{}
}

func (c ContractStoreAdapter) GetAllContracts(
	ctx context.Context,
	customer model.Customer) ([]model.Contract, error) {

	client, err := NewClientWithResponses("http://localhost:8080")
	if err != nil {
		return nil, err
	}

	// Per HTTPClient Daten abfragen
	response, err :=
		client.ListAllContractsWithResponse(ctx, customer.CustomerNo)
	if err != nil {
		return nil, err
	}
	// Auf Fehler prüfen
	if response.JSON200 == nil {
		return nil, errors.New("something wrong")
	}
	// Ergebnisdaten in richtiges Format wandeln
	var returnValue []model.Contract
	for _, contract := range *response.JSON200 {
		returnValue = append(returnValue,
			model.Contract{Name: contract.Name})
	}

	return returnValue, nil
}
