package handlers

import (
	"encoding/json"
	"fmt"
	"furry-sos-backend/config"
	"net/http"
)

type ShareRequest struct {
	UserID          int     `json:"user_id"`
	ReportID        int     `json:"report_id"`
	ReportType      string  `json:"report_type"`
	Platform        string  `json:"platform"`
	IsFundraising   bool    `json:"is_fundraising"`
	FundraisingGoal float64 `json:"fundraising_goal"`
	FundraisingBank string  `json:"fundraising_bank_account"`
}

func ShareCase(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	var req ShareRequest
	err := json.NewDecoder(r.Body).Decode(&req)
	if err != nil {
		http.Error(w, "Invalid request body", http.StatusBadRequest)
		return
	}

	shareURL := fmt.Sprintf("https://furry-sos.com/case/%s/%d", req.ReportType, req.ReportID)

	var animalType, locationAddr, imageURL string
	if req.ReportType == "emergency" {
		err = config.DB.QueryRow(`SELECT animal_type, location_address, image_url 
		                          FROM emergency_reports WHERE report_id = ?`,
			req.ReportID).Scan(&animalType, &locationAddr, &imageURL)
		if err != nil {
			http.Error(w, "Case not found", http.StatusNotFound)
			return
		}
	} else {
		err = config.DB.QueryRow(`SELECT animal_type, location_address, image_url 
		                          FROM deceased_reports WHERE report_id = ?`,
			req.ReportID).Scan(&animalType, &locationAddr, &imageURL)
		if err != nil {
			http.Error(w, "Case not found", http.StatusNotFound)
			return
		}
	}

	title := fmt.Sprintf("🐾 ช่วยเหลือสัตว์ฉุกเฉิน - เคส #%d", req.ReportID)
	desc := fmt.Sprintf("พบ%s ที่ %s กรุณาช่วยเหลือด้วย", animalType, locationAddr)

	createTableQuery := `CREATE TABLE IF NOT EXISTS shared_cases (
		share_id INT PRIMARY KEY AUTO_INCREMENT,
		user_id INT NOT NULL,
		report_id INT NOT NULL,
		report_type ENUM('emergency', 'deceased') NOT NULL,
		share_platform VARCHAR(50) NOT NULL,
		share_url VARCHAR(255) NOT NULL,
		share_title VARCHAR(200),
		share_description TEXT,
		share_image_url VARCHAR(255),
		is_fundraising BOOLEAN DEFAULT FALSE,
		fundraising_goal DECIMAL(15,2),
		fundraising_bank_account VARCHAR(50),
		created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
	)`
	config.DB.Exec(createTableQuery)

	query := `INSERT INTO shared_cases 
	          (user_id, report_id, report_type, share_platform, share_url, 
	           share_title, share_description, share_image_url, 
	           is_fundraising, fundraising_goal, fundraising_bank_account) 
	          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`

	_, err = config.DB.Exec(query,
		req.UserID, req.ReportID, req.ReportType, req.Platform, shareURL,
		title, desc, imageURL,
		req.IsFundraising, req.FundraisingGoal, req.FundraisingBank)
	if err != nil {
		http.Error(w, "Failed to share case: "+err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]interface{}{
		"message":   "✅ แชร์เคสสำเร็จ!",
		"share_url": shareURL,
		"case_card": map[string]interface{}{
			"title":       title,
			"description": desc,
			"image_url":   imageURL,
			"url":         shareURL,
			"animal":      animalType,
			"location":    locationAddr,
		},
	})
}
