package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	if len(os.Args) < 3 {
		fmt.Println("Usage: test-login <email> <password>")
		os.Exit(1)
	}

	email := os.Args[1]
	password := os.Args[2]

	// Try the guessed mutation format
	mutation := map[string]interface{}{
		"query": `mutation Login($email: String!, $password: String!) {
			login(email: $email, password: $password) {
				token
				refreshToken
				expiresIn
				user {
					id
					displayName
					username
				}
			}
		}`,
		"variables": map[string]interface{}{
			"email":    email,
			"password": password,
		},
	}

	jsonBody, err := json.MarshalIndent(mutation, "", "  ")
	if err != nil {
		fmt.Printf("Failed to marshal: %v\n", err)
		os.Exit(1)
	}

	fmt.Println("📤 Sending request:")
	fmt.Println(string(jsonBody))
	fmt.Println()

	req, err := http.NewRequest("POST", "https://engine.kosmi.io/", bytes.NewReader(jsonBody))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		os.Exit(1)
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Referer", "https://app.kosmi.io/")
	req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Request failed: %v\n", err)
		os.Exit(1)
	}
	defer resp.Body.Close()

	fmt.Printf("📥 Response Status: %d\n", resp.StatusCode)
	fmt.Println()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		os.Exit(1)
	}

	// Pretty print JSON response
	var result map[string]interface{}
	if err := json.Unmarshal(body, &result); err != nil {
		fmt.Println("Response (raw):")
		fmt.Println(string(body))
	} else {
		prettyJSON, _ := json.MarshalIndent(result, "", "  ")
		fmt.Println("Response (JSON):")
		fmt.Println(string(prettyJSON))
	}
}

