package services

import (
	"context"
	"fmt"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/sqs"
	"github.com/fgm/izidic"
)

func SQSClientService(dic *izidic.Container) (any, error) {
	ctx := context.Background()
	profile := dic.MustParam(PProfile).(string)
	region := dic.MustParam(PRegion).(string)
	epr := endpointResolver{region: region}
	cfg, err := config.LoadDefaultConfig(ctx,
		config.WithRegion(region),
		config.WithSharedConfigProfile(profile),
		config.WithEndpointResolverWithOptions(epr),
	)
	if err != nil {
		return nil, fmt.Errorf("failed loading default AWS config: %w", err)
	}

	client := sqs.NewFromConfig(cfg)
	return client, nil
}

type endpointResolver struct {
	region string
}

func (e endpointResolver) ResolveEndpoint(service, region string, options ...interface{}) (aws.Endpoint, error) {
	if service != `SQS` {
		return aws.Endpoint{}, fmt.Errorf("trying to Resolve non-SQS service: %s", service)
	}
	ep := aws.Endpoint{
		URL:               "http://localhost:4566/",
		HostnameImmutable: false,
		PartitionID:       "000000000000",
		SigningName:       "",
		SigningRegion:     e.region,
		SigningMethod:     "",
		Source:            0,
	}
	if region != "" {
		ep.URL = fmt.Sprintf("https://sqs.%s.amazonaws.com/", region)
	}
	return ep, nil
}
