// Carga personas y sus autorizaciones en el registro de habeas data desde un CSV.
//
// Uso (Go 1.21+, solo biblioteca estándar):
//
//	export INTEGRATION_API_TOKEN=nxl_...
//	export INTEGRATION_API_URL=http://localhost:4100/integration/v1   # opcional
//	go run main.go [ruta/al/archivo.csv]   # por defecto ../people.csv
//
// La Idempotency-Key se deriva del contenido de cada lote: volver a ejecutar el
// programa con el mismo archivo devuelve el resultado original (HTTP 200).
package main

import (
	"bytes"
	"crypto/sha256"
	"encoding/csv"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

const batchSize = 1000
const maxAttempts = 5

var (
	apiURL = strings.TrimRight(envOr("INTEGRATION_API_URL", "http://localhost:4100/integration/v1"), "/")
	token  = os.Getenv("INTEGRATION_API_TOKEN")
	client = &http.Client{Timeout: 60 * time.Second}
)

type authorization struct {
	AuthorizedOn      string `json:"authorizedOn"`
	Channel           string `json:"channel"`
	PolicyVersion     string `json:"policyVersion,omitempty"`
	EvidenceReference string `json:"evidenceReference,omitempty"`
}

type record struct {
	DocumentType   string        `json:"documentType"`
	DocumentNumber string        `json:"documentNumber"`
	FullName       string        `json:"fullName"`
	Email          string        `json:"email,omitempty"`
	Phone          string        `json:"phone,omitempty"`
	Authorization  authorization `json:"authorization"`
}

type batchResult struct {
	ID      string         `json:"id"`
	Counts  map[string]int `json:"counts"`
	Records []struct {
		Index  int    `json:"index"`
		Status string `json:"status"`
		Issues []struct{ Field, Code string }
	} `json:"records"`
}

func main() {
	if token == "" {
		fail("Defina INTEGRATION_API_TOKEN con el token creado en el portal (Integraciones).")
	}
	csvPath := filepath.Join("..", "people.csv")
	if len(os.Args) > 1 {
		csvPath = os.Args[1]
	}

	var ping struct {
		Tenant struct{ Name string }
		Token  struct{ Scopes []string }
	}
	request("GET", "/ping", nil, "", &ping)
	fmt.Printf("Conectado a %s · permisos: %s\n", ping.Tenant.Name, strings.Join(ping.Token.Scopes, ", "))

	records := readRecords(csvPath)
	for start := 0; start < len(records); start += batchSize {
		end := min(start+batchSize, len(records))
		body, _ := json.Marshal(map[string]any{"externalReference": filepath.Base(csvPath), "records": records[start:end]})
		sum := sha256.Sum256(body)
		key := "personas-" + hex.EncodeToString(sum[:])[:32]

		var batch batchResult
		res := request("POST", "/authorizations", body, key, &batch)
		replayed := ""
		if res.Header.Get("Idempotent-Replayed") == "true" {
			replayed = " (reintento: resultado original)"
		}
		fmt.Printf("\nLote %s · HTTP %d%s\n", batch.ID, res.StatusCode, replayed)
		fmt.Printf("  received: %d · created: %d · updated: %d · unchanged: %d · duplicate: %d · rejected: %d\n",
			batch.Counts["received"], batch.Counts["created"], batch.Counts["updated"],
			batch.Counts["unchanged"], batch.Counts["duplicate"], batch.Counts["rejected"])
		for _, r := range batch.Records {
			if r.Status != "rejected" {
				continue
			}
			issues := make([]string, len(r.Issues))
			for i, issue := range r.Issues {
				issues[i] = fmt.Sprintf("%s (%s)", issue.Field, issue.Code)
			}
			// La línea 1 del CSV es el encabezado.
			fmt.Printf("  Rechazado · línea %d del CSV: %s\n", start+r.Index+2, strings.Join(issues, ", "))
		}
	}
}

// request envía la solicitud y decodifica la respuesta en out. Reintenta
// errores de red, 409, 429 y 5xx, siempre con el mismo cuerpo.
func request(method, path string, body []byte, idempotencyKey string, out any) *http.Response {
	for attempt := 1; ; attempt++ {
		wait := time.Duration(1<<(attempt-1)) * time.Second
		req, _ := http.NewRequest(method, apiURL+path, bytes.NewReader(body))
		req.Header.Set("Authorization", "Bearer "+token)
		if body != nil {
			req.Header.Set("Content-Type", "application/json")
			req.Header.Set("Idempotency-Key", idempotencyKey)
		}
		res, err := client.Do(req)
		if err == nil {
			data, _ := io.ReadAll(res.Body)
			res.Body.Close()
			if res.StatusCode < 300 {
				if err := json.Unmarshal(data, out); err != nil {
					fail("Respuesta inesperada: " + err.Error())
				}
				return res
			}
			retryable := res.StatusCode == 409 || res.StatusCode == 429 || res.StatusCode >= 500
			if !retryable || attempt == maxAttempts {
				var e struct{ Error struct{ Code, Message string } }
				json.Unmarshal(data, &e)
				fail(fmt.Sprintf("Error %d %s: %s", res.StatusCode, e.Error.Code, e.Error.Message))
			}
			if s, err := strconv.Atoi(res.Header.Get("Retry-After")); err == nil && s > 0 {
				wait = time.Duration(s) * time.Second
			}
		} else if attempt == maxAttempts {
			fail("No se pudo conectar con la API: " + err.Error())
		}
		fmt.Printf("  Reintento %d/%d en %s…\n", attempt, maxAttempts-1, wait)
		time.Sleep(wait)
	}
}

// readRecords convierte cada fila del CSV en un registro de la API.
func readRecords(path string) []record {
	f, err := os.Open(path)
	if err != nil {
		fail("No se pudo abrir el CSV: " + err.Error())
	}
	defer f.Close()
	rows, err := csv.NewReader(f).ReadAll()
	if err != nil {
		fail("CSV inválido: " + err.Error())
	}
	col := map[string]int{}
	for i, name := range rows[0] {
		col[name] = i
	}
	records := make([]record, 0, len(rows)-1)
	for _, row := range rows[1:] {
		get := func(name string) string { return strings.TrimSpace(row[col[name]]) }
		records = append(records, record{
			DocumentType: get("documentType"), DocumentNumber: get("documentNumber"), FullName: get("fullName"),
			Email: get("email"), Phone: get("phone"),
			Authorization: authorization{
				AuthorizedOn: get("authorizedOn"), Channel: get("channel"),
				PolicyVersion: get("policyVersion"), EvidenceReference: get("evidenceReference"),
			},
		})
	}
	return records
}

func envOr(name, fallback string) string {
	if v := os.Getenv(name); v != "" {
		return v
	}
	return fallback
}

func fail(message string) {
	fmt.Fprintln(os.Stderr, message)
	os.Exit(1)
}
