package handlers

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strings"

	"furry-sos-backend/config"
)

// ======================================================
// GET VOLUNTEER DECEASED CASES (งานเก็บกู้ซากสัตว์)
// GET /api/volunteer/deceased-cases
// Header: X-User-ID
//
// ✅ แก้: เพิ่ม severity_level + ORDER BY severity
// ======================================================
func GetVolunteerDeceasedCases(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	userID, err := getVolunteerUserID(r)
	if err != nil {
		w.WriteHeader(http.StatusUnauthorized)
		json.NewEncoder(w).Encode(map[string]interface{}{
			"success": false,
			"message": "ไม่พบ User ID",
		})
		return
	}

	role, err := getUserRole(userID)
	if err != nil || role != "volunteer" {
		w.WriteHeader(http.StatusForbidden)
		json.NewEncoder(w).Encode(map[string]interface{}{
			"success": false,
			"message": "บัญชีนี้ไม่ใช่อาสาสมัคร",
		})
		return
	}

	// ดึง working area
	var workingArea string
	err = config.DB.QueryRow(`
		SELECT COALESCE(working_area, '')
		FROM volunteers
		WHERE user_id = ? AND is_approved = 1
		LIMIT 1
	`, userID).Scan(&workingArea)

	if err != nil {
		w.WriteHeader(http.StatusNotFound)
		json.NewEncoder(w).Encode(map[string]interface{}{
			"success": false,
			"message": "ไม่พบข้อมูลพื้นที่ของอาสาสมัคร",
		})
		return
	}

	workingArea = strings.TrimSpace(workingArea)

	// ✅ ดึงเคสซากสัตว์ + severity_level + ORDER BY severity
	rows, err := config.DB.Query(`
		SELECT 
			report_id,
			animal_type,
			COALESCE(location_address, '') AS location_address,
			COALESCE(location_lat, 0) AS location_lat,
			COALESCE(location_lng, 0) AS location_lng,
			COALESCE(image_url, '') AS image_url,
			COALESCE(notes, '') AS notes,
			COALESCE(province, '') AS province,
			COALESCE(severity_level, 'low') AS severity_level,
			status,
			created_at
		FROM deceased_reports
		WHERE status = 'pending' AND assigned_volunteer_id IS NULL
		ORDER BY 
			CASE LOWER(COALESCE(severity_level, 'low'))
				WHEN 'critical' THEN 1
				WHEN 'high' THEN 2
				WHEN 'medium' THEN 3
				WHEN 'low' THEN 4
				ELSE 5
			END ASC,
			created_at DESC
	`)

	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		json.NewEncoder(w).Encode(map[string]interface{}{
			"success": false,
			"message": "ไม่สามารถโหลดรายการงานได้: " + err.Error(),
		})
		return
	}
	defer rows.Close()

	cases := make([]map[string]interface{}, 0)

	for rows.Next() {
		var (
			reportID        int
			animalType      string
			locationAddress string
			locationLat     float64
			locationLng     float64
			imageURL        string
			notes           string
			province        string
			severityLevel   string     // ✅ เพิ่ม
			status          string
			createdAt       interface{}
		)

		err := rows.Scan(
			&reportID, &animalType, &locationAddress,
			&locationLat, &locationLng, &imageURL,
			&notes, &province, &severityLevel,  // ✅ เพิ่ม
			&status, &createdAt,
		)
		if err != nil {
			continue
		}

		// ✅ Generate case_code จาก report_id (เพราะตารางไม่มีคอลัมน์นี้)
		caseCode := fmt.Sprintf("BR-%04d", reportID)

		cases = append(cases, map[string]interface{}{
			"report_id":        reportID,
			"case_code":        caseCode,
			"case_type":        "deceased",
			"animal_type":      animalType,
			"location_address": locationAddress,
			"location_lat":     locationLat,
			"location_lng":     locationLng,
			"province":         province,
			"image_url":        imageURL,
			"notes":            notes,
			"severity_level":   severityLevel,   // ✅ เพิ่ม
			"status":           status,
			"created_at":       createdAt,
		})
	}

	json.NewEncoder(w).Encode(map[string]interface{}{
		"success":      true,
		"user_id":      userID,
		"working_area": workingArea,
		"count":        len(cases),
		"cases":        cases,
	})
}