package handlers

import (
	"encoding/json"
	"net/http"
	"strconv"

	"github.com/rede5/gohorsejobs/backend/internal/dto"
	"github.com/rede5/gohorsejobs/backend/internal/services"
)

type JobHandler struct {
	Service *services.JobService
}

func NewJobHandler(service *services.JobService) *JobHandler {
	return &JobHandler{Service: service}
}

func (h *JobHandler) GetJobs(w http.ResponseWriter, r *http.Request) {
	page, _ := strconv.Atoi(r.URL.Query().Get("page"))
	limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
	companyID, _ := strconv.Atoi(r.URL.Query().Get("companyId"))

	filter := dto.JobFilterQuery{
		PaginationQuery: dto.PaginationQuery{
			Page:  page,
			Limit: limit,
		},
	}
	if companyID > 0 {
		filter.CompanyID = &companyID
	}

	jobs, total, err := h.Service.GetJobs(filter)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	response := dto.PaginatedResponse{
		Data: jobs,
		Pagination: dto.Pagination{
			Page:  page,
			Limit: limit,
			Total: total,
		},
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)
}

func (h *JobHandler) CreateJob(w http.ResponseWriter, r *http.Request) {
	var req dto.CreateJobRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	// Validate request (omitted for brevity, assume validation middleware or service validation)

	job, err := h.Service.CreateJob(req)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(job)
}

func (h *JobHandler) GetJobByID(w http.ResponseWriter, r *http.Request) {
	idStr := r.PathValue("id") // Go 1.22+ routing
	if idStr == "" {
		// Fallback for older Go versions or if not using PathValue compatible mux
		// But let's assume standard mux or we might need to parse URL
		// For now, let's assume we can get it from context or URL
		// If using standard http.ServeMux in Go 1.22, PathValue works.
		// If not, we might need a helper.
		// Let's assume standard mux with Go 1.22 for now as it's modern.
		// If not, we'll fix it.
		// Actually, let's check go.mod version.
	}

	// Wait, I should check go.mod version to be safe.
	// But let's write standard code.

	// Assuming we use a router that puts params in context or we parse URL.
	// Since I am editing router.go later, I can ensure we use Go 1.22 patterns or a library.
	// The existing router.go used `mux.HandleFunc("/jobs", ...)` which suggests standard lib.

	// Let's try to parse from URL path if PathValue is not available (it is in Go 1.22).
	// I'll use a helper to extract ID from URL for now to be safe if I'm not sure about Go version.
	// But `r.PathValue` is the way forward.

	id, err := strconv.Atoi(idStr)
	if err != nil {
		http.Error(w, "Invalid job ID", http.StatusBadRequest)
		return
	}

	job, err := h.Service.GetJobByID(id)
	if err != nil {
		http.Error(w, err.Error(), http.StatusNotFound)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(job)
}

func (h *JobHandler) UpdateJob(w http.ResponseWriter, r *http.Request) {
	idStr := r.PathValue("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		http.Error(w, "Invalid job ID", http.StatusBadRequest)
		return
	}

	var req dto.UpdateJobRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	job, err := h.Service.UpdateJob(id, req)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(job)
}

func (h *JobHandler) DeleteJob(w http.ResponseWriter, r *http.Request) {
	idStr := r.PathValue("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		http.Error(w, "Invalid job ID", http.StatusBadRequest)
		return
	}

	if err := h.Service.DeleteJob(id); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
