package handlers

import (
	"encoding/json"
	"furry-sos-backend/config"
	"net/http"
)

// ======================================================
// 🏥 GET ALL HOSPITALS
// GET /api/hospitals
// ======================================================
func GetHospitals(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	// 🌟 เพิ่ม review_count เข้ามาด้วย
	query := `
		SELECT 
			h.hospital_id, 
			h.name, 
			h.address, 
			h.phone, 
			h.latitude, 
			h.longitude,
			h.is_24_hours, 
			h.is_partner, 
			COALESCE(h.rating, 0) AS rating,
			(
				SELECT COUNT(*) 
				FROM hospital_reviews hr 
				WHERE hr.hospital_id = h.hospital_id
			) AS review_count
		FROM hospitals h
		ORDER BY h.rating DESC
	`

	rows, err := config.DB.Query(query)
	if err != nil {
		http.Error(w, "โหลดข้อมูลโรงพยาบาลไม่ได้: "+err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	hospitals := []map[string]interface{}{}

	for rows.Next() {
		var (
			hospitalID  int
			name        string
			address     string
			phone       string
			latitude    float64
			longitude   float64
			is24Hours   bool
			isPartner   bool
			rating      float64
			reviewCount int
		)

		err := rows.Scan(
			&hospitalID,
			&name,
			&address,
			&phone,
			&latitude,
			&longitude,
			&is24Hours,
			&isPartner,
			&rating,
			&reviewCount,
		)
		if err != nil {
			continue
		}

		hospitals = append(hospitals, map[string]interface{}{
			"hospital_id":  hospitalID,
			"name":         name,
			"address":      address,
			"phone":        phone,
			"latitude":     latitude,
			"longitude":    longitude,
			"is_24_hours":  is24Hours,
			"is_partner":   isPartner,
			"rating":       rating,
			"review_count": reviewCount, // 🌟 ส่งกลับด้วย
		})
	}

	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	json.NewEncoder(w).Encode(hospitals)
}

// ======================================================
// 🌙 GET 24-HOUR HOSPITALS
// GET /api/hospitals/24h
// ======================================================
func Get24HourHospitals(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	// 🌟 เพิ่ม review_count เข้ามาด้วย
	query := `
		SELECT 
			h.hospital_id, 
			h.name, 
			h.address, 
			h.phone, 
			h.latitude, 
			h.longitude, 
			COALESCE(h.rating, 0) AS rating,
			(
				SELECT COUNT(*) 
				FROM hospital_reviews hr 
				WHERE hr.hospital_id = h.hospital_id
			) AS review_count
		FROM hospitals h
		WHERE h.is_24_hours = TRUE 
		ORDER BY h.rating DESC
	`

	rows, err := config.DB.Query(query)
	if err != nil {
		http.Error(w, "โหลดข้อมูลโรงพยาบาลไม่ได้: "+err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	hospitals := []map[string]interface{}{}

	for rows.Next() {
		var (
			hospitalID  int
			name        string
			address     string
			phone       string
			latitude    float64
			longitude   float64
			rating      float64
			reviewCount int
		)

		err := rows.Scan(
			&hospitalID,
			&name,
			&address,
			&phone,
			&latitude,
			&longitude,
			&rating,
			&reviewCount,
		)
		if err != nil {
			continue
		}

		hospitals = append(hospitals, map[string]interface{}{
			"hospital_id":  hospitalID,
			"name":         name,
			"address":      address,
			"phone":        phone,
			"latitude":     latitude,
			"longitude":    longitude,
			"is_24_hours":  true,
			"rating":       rating,
			"review_count": reviewCount, // 🌟 ส่งกลับด้วย
		})
	}

	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	json.NewEncoder(w).Encode(hospitals)
}