// Package api provides HTTP handlers for camera operations.
package api

import (
	"log"
	"net/http"

	"github.com/cubecraft/remoterig/internal/db"
	"github.com/go-chi/chi/v5"
)

// StartRecording returns a handler for POST /cameras/{id}/start.
func StartRecording(database *db.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		cameraID := chi.URLParam(r, "id")
		if cameraID == "" {
			respondJSON(w, http.StatusBadRequest, map[string]string{"error": "camera_id required"})
			return
		}

		// Check if camera is registered
		var exists int
		err := database.QueryRowContext(r.Context(),
			"SELECT COUNT(*) FROM cameras WHERE camera_id = ?", cameraID).Scan(&exists)
		if err != nil || exists == 0 {
			respondJSON(w, http.StatusNotFound, map[string]string{"error": "camera not registered"})
			return
		}

		// Open recording event
		result, err := database.ExecContext(r.Context(), `
			INSERT INTO recording_events (camera_id, started_at, reason)
			VALUES (?, datetime('now'), 'manual')
		`, cameraID)
		if err != nil {
			log.Printf("Error starting recording: %v", err)
			respondJSON(w, http.StatusInternalServerError, map[string]string{"error": "database error"})
			return
		}

		rows, _ := result.RowsAffected()
		log.Printf("Recording started on %s (%d rows affected)", cameraID, rows)

		respondJSON(w, http.StatusOK, map[string]string{
			"status":    "recording_started",
			"camera_id": cameraID,
		})
	}
}

// StopRecording returns a handler for POST /cameras/{id}/stop.
func StopRecording(database *db.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		cameraID := chi.URLParam(r, "id")
		if cameraID == "" {
			respondJSON(w, http.StatusBadRequest, map[string]string{"error": "camera_id required"})
			return
		}

		// Check if camera is registered
		var exists int
		err := database.QueryRowContext(r.Context(),
			"SELECT COUNT(*) FROM cameras WHERE camera_id = ?", cameraID).Scan(&exists)
		if err != nil || exists == 0 {
			respondJSON(w, http.StatusNotFound, map[string]string{"error": "camera not registered"})
			return
		}

		// Close the most recent open recording event
		result, err := database.ExecContext(r.Context(), `
			UPDATE recording_events SET stopped_at = datetime('now'), reason = 'manual'
			WHERE camera_id = ? AND stopped_at IS NULL
		`, cameraID)
		if err != nil {
			log.Printf("Error stopping recording: %v", err)
			respondJSON(w, http.StatusInternalServerError, map[string]string{"error": "database error"})
			return
		}

		rows, _ := result.RowsAffected()
		log.Printf("Recording stopped on %s (%d rows affected)", cameraID, rows)

		respondJSON(w, http.StatusOK, map[string]string{
			"status":    "recording_stopped",
			"camera_id": cameraID,
		})
	}
}
