package handlers

import (
	"database/sql"
	"encoding/json"
	"furry-sos-backend/config"
	"net/http"
	"strconv"
	"strings"
)

// ============================================
// 📍 GET CASE TRACKING
// ============================================

func GetCaseTracking(w http.ResponseWriter, r *http.Request) {

	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	var reportID string
	var reportType string

	// =========================================================
	// 1. QUERY PARAM
	// =========================================================

	reportID = r.URL.Query().Get("report_id")
	reportType = r.URL.Query().Get("type")

	if reportType == "" {
		reportType = r.URL.Query().Get("report_type")
	}

	// =========================================================
	// 2. PATH PARAM
	// =========================================================

	if reportID == "" || reportType == "" {
		path := strings.Trim(r.URL.Path, "/")
		parts := strings.Split(path, "/")

		if len(parts) >= 5 &&
			parts[0] == "api" &&
			parts[1] == "reports" &&
			parts[4] == "tracking" {

			if reportType == "" {
				reportType = parts[2]
			}
			if reportID == "" {
				reportID = parts[3]
			}
		}
	}

	println("======================================")
	println("📍 GET CASE TRACKING")
	println("PATH =", r.URL.Path)
	println("report_id =", reportID)
	println("report_type =", reportType)
	println("======================================")

	// =========================================================
	// VALIDATE
	// =========================================================

	if reportID == "" {
		http.Error(w, "Missing parameter: report_id", http.StatusBadRequest)
		return
	}

	if reportType == "" {
		http.Error(w, "Missing parameter: report_type", http.StatusBadRequest)
		return
	}

	reportIDInt, err := strconv.Atoi(reportID)

	if err != nil || reportIDInt <= 0 {
		http.Error(w, "Invalid report_id", http.StatusBadRequest)
		return
	}

	reportType = strings.ToLower(strings.TrimSpace(reportType))

	if reportType != "emergency" && reportType != "deceased" {
		http.Error(w, "Invalid report_type", http.StatusBadRequest)
		return
	}

	// =========================================================
	// CURRENT STATUS
	// =========================================================

	currentStatus := map[string]interface{}{
		"status":      "pending",
		"description": "รอการรับเรื่อง",
		"created_at":  "",
		"created_by":  "system",
	}

	currentQuery := `
		SELECT
			status,
			status_description,
			created_at,
			created_by
		FROM case_tracking
		WHERE report_id = ?
		  AND report_type = ?
		  AND is_current = TRUE
		ORDER BY tracking_id DESC
		LIMIT 1
	`

	var (
		status    string
		desc      string
		createdAt string
		createdBy string
	)

	err = config.DB.QueryRow(
		currentQuery,
		reportIDInt,
		reportType,
	).Scan(
		&status,
		&desc,
		&createdAt,
		&createdBy,
	)

	if err == nil {
		currentStatus["status"] = status
		currentStatus["description"] = desc
		currentStatus["created_at"] = createdAt
		currentStatus["created_by"] = createdBy
	}

	// =========================================================
	// HISTORY
	// =========================================================

	historyQuery := `
		SELECT
			status,
			status_description,
			created_at,
			created_by
		FROM case_tracking
		WHERE report_id = ?
		  AND report_type = ?
		ORDER BY status_order ASC, tracking_id ASC
	`

	rows, err := config.DB.Query(
		historyQuery,
		reportIDInt,
		reportType,
	)

	if err != nil {
		http.Error(w, "Failed to get history: "+err.Error(), http.StatusInternalServerError)
		return
	}

	defer rows.Close()

	history := make([]map[string]interface{}, 0)

	for rows.Next() {
		var (
			s  string
			d  string
			c  string
			cb string
		)

		err := rows.Scan(&s, &d, &c, &cb)
		if err != nil {
			continue
		}

		history = append(history, map[string]interface{}{
			"status":      s,
			"description": d,
			"created_at":  c,
			"created_by":  cb,
		})
	}

	if len(history) == 0 {
		history = append(history, currentStatus)
	}

	// =========================================================
	// ✅ VOLUNTEER INFO (ใหม่!)
	// ดึงข้อมูลอาสาสมัครที่รับเคสนี้
	// =========================================================

	volunteerData := map[string]interface{}{
		"volunteer_id": 0,
		"user_id":      0,
		"full_name":    "",
		"phone":        "",
	}

	// ดึง volunteer_id ที่ผูกกับเคสนี้
	var assignedVolunteerID sql.NullInt64

	var assignedQuery string

	if reportType == "emergency" {
		assignedQuery = `
			SELECT assigned_volunteer_id
			FROM emergency_reports
			WHERE report_id = ?
		`
	} else {
		assignedQuery = `
			SELECT assigned_volunteer_id
			FROM deceased_reports
			WHERE report_id = ?
		`
	}

	err = config.DB.QueryRow(
		assignedQuery,
		reportIDInt,
	).Scan(&assignedVolunteerID)

	if err == nil && assignedVolunteerID.Valid && assignedVolunteerID.Int64 > 0 {

		// ดึงข้อมูลอาสา + user
		volunteerQuery := `
			SELECT
				v.volunteer_id,
				v.user_id,
				COALESCE(u.full_name, 'อาสาสมัคร') AS full_name,
				COALESCE(u.phone, '') AS phone
			FROM volunteers v
			INNER JOIN users u ON v.user_id = u.user_id
			WHERE v.volunteer_id = ?
		`

		var (
			vid      int
			uid      int
			fullName string
			phone    string
		)

		err = config.DB.QueryRow(
			volunteerQuery,
			assignedVolunteerID.Int64,
		).Scan(&vid, &uid, &fullName, &phone)

		if err == nil {
			volunteerData["volunteer_id"] = vid
			volunteerData["user_id"] = uid
			volunteerData["full_name"] = fullName
			volunteerData["phone"] = phone

			println("✅ Volunteer info:")
			println("  volunteer_id =", vid)
			println("  user_id =", uid)
			println("  full_name =", fullName)
			println("  phone =", phone)

		} else {
			println("⚠️ ไม่พบข้อมูลอาสา volunteer_id =", assignedVolunteerID.Int64)
			println("  error =", err.Error())
		}

	} else {
		println("ℹ️ ยังไม่มีอาสารับเคสนี้")
	}

	// =========================================================
	// RESPONSE
	// =========================================================

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)

	json.NewEncoder(w).Encode(map[string]interface{}{
		"success":     true,
		"report_id":   reportIDInt,
		"report_type": reportType,
		"current":     currentStatus,
		"history":     history,
		"volunteer":   volunteerData, // ✅ เพิ่ม!
	})
}
