package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"time"

	"api-service/internal/config"
	services "api-service/internal/services/satusehat"

	"github.com/joho/godotenv"
)

func main() {
	fmt.Println("SatuSehat Specific Requests - Organization & Patient by NIK")
	fmt.Println("==========================================================")

	// Load environment variables from .env file
	err := godotenv.Load("../.env")
	if err != nil {
		log.Printf("Warning: Could not load .env file: %v", err)
	}

	// Set debug logging
	os.Setenv("LOG_LEVEL", "debug")

	// Load configuration from environment variables
	cfg := config.LoadConfig()

	// Create SatuSehat service
	service := services.NewSatuSehatServiceFromConfig(cfg)

	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()

	// Test 1: Get Organization by ID (using OrgID from config)
	fmt.Println("\n1. Get Organization by ID:")
	orgID := cfg.SatuSehat.OrgID
	fmt.Printf("   Using OrgID: %s\n", orgID)

	orgEndpoint := fmt.Sprintf("/Organization/%s", orgID)
	orgResult, err := service.GetRawResponse(ctx, orgEndpoint)
	if err != nil {
		log.Printf("Error getting organization: %v", err)
	} else {
		fmt.Printf("   Status Code: %d\n", orgResult.StatusCode)
		fmt.Printf("   Success: %v\n", orgResult.Success)
		fmt.Printf("   Message: %s\n", orgResult.Message)

		if orgResult.Data != nil {
			fmt.Printf("   Data Type: %T\n", orgResult.Data)

			// Convert data to JSON for better readability
			if jsonData, err := json.MarshalIndent(orgResult.Data, "   ", "  "); err == nil {
				fmt.Printf("   Organization Data: \n%s\n", string(jsonData))
			} else {
				fmt.Printf("   Data (raw): %+v\n", orgResult.Data)
			}
		}

		if orgResult.Error != nil {
			fmt.Printf("   Error Code: %s\n", orgResult.Error.Code)
			fmt.Printf("   Error Details: %s\n", orgResult.Error.Details)
		}
	}

	// Test 2: Get Patient by specific NIK
	fmt.Println("\n2. Get Patient by Specific NIK:")
	specificNIK := "3512162601960002"
	fmt.Printf("   Using NIK: %s\n", specificNIK)

	patientResult, err := service.GetPatientByNIK(ctx, specificNIK)
	if err != nil {
		log.Printf("Error getting patient: %v", err)
	} else {
		fmt.Printf("   Status Code: %d\n", patientResult.StatusCode)
		fmt.Printf("   Success: %v\n", patientResult.Success)
		fmt.Printf("   Message: %s\n", patientResult.Message)

		if patientResult.Data != nil {
			fmt.Printf("   Data Type: %T\n", patientResult.Data)

			// Convert data to JSON for better readability
			if jsonData, err := json.MarshalIndent(patientResult.Data, "   ", "  "); err == nil {
				fmt.Printf("   Patient Data: \n%s\n", string(jsonData))

				// Extract and display specific patient information
				displayPatientDetails(patientResult.Data)
			} else {
				fmt.Printf("   Data (raw): %+v\n", patientResult.Data)
			}
		}

		if patientResult.Error != nil {
			fmt.Printf("   Error Code: %s\n", patientResult.Error.Code)
			fmt.Printf("   Error Details: %s\n", patientResult.Error.Details)
		}
	}

	// Test 3: Health check to verify token status
	fmt.Println("\n3. Service Health Check:")
	isValid := service.IsTokenValid()
	fmt.Printf("   Token Valid: %v\n", isValid)

	if !isValid {
		fmt.Println("   Refreshing token...")
		err = service.RefreshToken(ctx)
		if err != nil {
			log.Printf("Error refreshing token: %v", err)
		} else {
			fmt.Println("   Token refreshed successfully")
			fmt.Printf("   Token Valid After Refresh: %v\n", service.IsTokenValid())
		}
	}

	fmt.Println("\nSpecific requests test completed!")
}

// displayPatientDetails extracts and displays specific patient information from FHIR response
func displayPatientDetails(data interface{}) {
	fmt.Println("\n   --- Patient Details ---")

	// Convert to map for easier access
	if dataMap, ok := data.(map[string]interface{}); ok {
		// Check if it's a Bundle
		if resourceType, exists := dataMap["resourceType"]; exists && resourceType == "Bundle" {
			if entries, exists := dataMap["entry"]; exists {
				if entryList, ok := entries.([]interface{}); ok && len(entryList) > 0 {
					if firstEntry, ok := entryList[0].(map[string]interface{}); ok {
						if resource, exists := firstEntry["resource"]; exists {
							if patient, ok := resource.(map[string]interface{}); ok {
								// Display basic patient info
								fmt.Printf("   Patient ID: %v\n", patient["id"])

								// Display name
								if names, exists := patient["name"].([]interface{}); exists && len(names) > 0 {
									if name, ok := names[0].(map[string]interface{}); ok {
										fmt.Printf("   Name: %v\n", name["text"])
									}
								}

								// Display identifiers
								if identifiers, exists := patient["identifier"].([]interface{}); exists {
									fmt.Println("   Identifiers:")
									for _, ident := range identifiers {
										if identifier, ok := ident.(map[string]interface{}); ok {
											system := identifier["system"]
											value := identifier["value"]
											fmt.Printf("     - %s: %v\n", system, value)
										}
									}
								}

								// Display status
								fmt.Printf("   Active: %v\n", patient["active"])

								// Display meta information
								if meta, exists := patient["meta"].(map[string]interface{}); exists {
									fmt.Printf("   Last Updated: %v\n", meta["lastUpdated"])
									if profiles, exists := meta["profile"].([]interface{}); exists {
										fmt.Printf("   FHIR Profile: %v\n", profiles[0])
									}
								}
							}
						}
					}
				}
			}
		}
	}
	fmt.Println("   -----------------------")
}
