package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/credentials"
	"github.com/aws/aws-sdk-go-v2/service/s3"
)

func main() {
	// Hardcoded values for debugging to avoid .env loading issues
	endpoint := "https://objectstore.nyc1.civo.com"
	accessKey := "0UZ69TH03Q292DMTB82B"
	secretKey := "JJ5XXZYvoWdnqBCNP5oREjACyrXeH6EgSqeSybT7"
	bucket := "rede5/ghorsejobs-dev"
	region := "nyc1"

	fmt.Printf("Loaded Env:\nEndpoint: %s\nAccess: %s\nSecret: %s\nBucket: %s\nRegion: %s\n\n",
		endpoint, accessKey, secretKey, bucket, region)

	// Test 1: Configured values
	fmt.Println("--- TEST 1: Configured Values ---")
	testS3(endpoint, accessKey, secretKey, bucket, region)

	// Test 2: Force us-east-1
	fmt.Println("\n--- TEST 2: Force us-east-1 ---")
	testS3(endpoint, accessKey, secretKey, bucket, "us-east-1")

	// Test 3: Split bucket (if contains slash)
	if strings.Contains(bucket, "/") {
		parts := strings.SplitN(bucket, "/", 2)
		realBucket := parts[0]
		// keyPrefix := parts[1] // Not used for list, but good to know
		fmt.Printf("\n--- TEST 3: Bucket base '%s' (Region: %s) ---\n", realBucket, region)
		testS3(endpoint, accessKey, secretKey, realBucket, region)

		fmt.Printf("\n--- TEST 4: Bucket base '%s' (Region: us-east-1) ---\n", realBucket)
		testS3(endpoint, accessKey, secretKey, realBucket, "us-east-1")
	}
}

func testS3(endpoint, access, secret, bucket, region string) {
	cfg, err := config.LoadDefaultConfig(context.TODO(),
		config.WithRegion(region),
		config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(access, secret, "")),
	)
	if err != nil {
		fmt.Printf("Error loading config: %v\n", err)
		return
	}

	client := s3.NewFromConfig(cfg, func(o *s3.Options) {
		o.BaseEndpoint = aws.String(endpoint)
		o.UsePathStyle = true
		o.Region = region
	})

	// Try List Objects
	fmt.Printf("Attempting ListObjectsV2 on bucket '%s'...\n", bucket)
	out, err := client.ListObjectsV2(context.TODO(), &s3.ListObjectsV2Input{
		Bucket:  aws.String(bucket),
		MaxKeys: aws.Int32(1),
	})

	if err != nil {
		fmt.Printf("FAILED: %v\n", err)
	} else {
		fmt.Printf("SUCCESS! Found %d objects.\n", len(out.Contents))
		if len(out.Contents) > 0 {
			fmt.Printf("Sample object: %s\n", *out.Contents[0].Key)
		}
	}
}
