package handler

import (
	"encoding/json"
	"fmt"
	"lune/talentscale/internal/domain"
	"lune/talentscale/internal/pkg/firebase"
	"net/http"
	"path/filepath"
	"strings"
	"time"

	"github.com/google/uuid"
)

type ProfileHandler struct {
	usecase domain.CandidateUsecase
	storage firebase.StorageService
}

func NewProfileHandler(u domain.CandidateUsecase, s firebase.StorageService) *ProfileHandler {
	return &ProfileHandler{usecase: u, storage: s}
}

// UpdateProfile - POST /api/candidate/profile
func (h *ProfileHandler) UpdateProfile(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		h.respondError(w, http.StatusMethodNotAllowed, "Method not allowed")
		return
	}

	// 1. Get Candidate ID from context
	candidateIDVal := r.Context().Value("candidate_id")
	var candidateID uuid.UUID
	if id, ok := candidateIDVal.(uuid.UUID); ok {
		candidateID = id
	} else if idStr, ok := candidateIDVal.(string); ok {
		candidateID, _ = uuid.Parse(idStr)
	}

	if candidateID == uuid.Nil {
		idHeader := r.Header.Get("X-Candidate-ID")
		if idHeader != "" {
			candidateID, _ = uuid.Parse(idHeader)
		} else {
			h.respondError(w, http.StatusUnauthorized, "Unauthorized: Candidate session not found")
			return
		}
	}

	// 2. Parse Multipart Form
	err := r.ParseMultipartForm(10 << 20) // 10MB max
	if err != nil {
		h.respondError(w, http.StatusBadRequest, "Failed to parse form: "+err.Error())
		return
	}

	phone := r.FormValue("phone")
	if phone == "" {
		h.respondError(w, http.StatusBadRequest, "Phone number is required")
		return
	}

	file, header, err := r.FormFile("resume_file")
	if err != nil {
		h.respondError(w, http.StatusBadRequest, "Resume file is required")
		return
	}
	defer file.Close()

	// 3. Validate File Extension
	ext := strings.ToLower(filepath.Ext(header.Filename))
	if ext != ".pdf" && ext != ".doc" && ext != ".docx" {
		h.respondError(w, http.StatusBadRequest, "Invalid file format. Only PDF, DOC, and DOCX are allowed")
		return
	}

	// 4. Upload File to Firebase
	// Path: candidate/candidate_uuid/namafile.extensions
	firebasePath := fmt.Sprintf("candidate/%s/%s", candidateID.String(), header.Filename)
	contentType := header.Header.Get("Content-Type")

	publicURL, err := h.storage.UploadFile(r.Context(), file, firebasePath, contentType)
	if err != nil {
		h.respondError(w, http.StatusInternalServerError, "Failed to upload file to firebase: "+err.Error())
		return
	}

	// 5. Update Database via Usecase
	candidate := &domain.Candidate{
		ID:         candidateID,
		Phone:      phone,
		ResumeFile: publicURL,
		UpdatedAt:  time.Now(),
	}

	if err := h.usecase.UpdateProfile(r.Context(), candidate); err != nil {
		h.respondError(w, http.StatusInternalServerError, "Failed to update profile: "+err.Error())
		return
	}

	// 6. Response
	h.respondJSON(w, http.StatusOK, map[string]interface{}{
		"success": true,
		"message": "Profile updated successfully",
		"data": map[string]string{
			"resume_url": publicURL,
		},
	})
}

func (h *ProfileHandler) respondJSON(w http.ResponseWriter, code int, payload interface{}) {
	response, _ := json.Marshal(payload)
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	w.Write(response)
}

func (h *ProfileHandler) respondError(w http.ResponseWriter, code int, message string) {
	h.respondJSON(w, code, map[string]interface{}{
		"success": false,
		"error":   message,
	})
}
