package handler

import (
	"log"
	"lune/talentscale/internal/domain"
	"lune/talentscale/internal/pkg/ctxval"
	"lune/talentscale/pkg/response"
	"strconv"

	"github.com/gofiber/fiber/v2"
	"github.com/google/uuid"
)

type TestSessionHandler struct {
	usecase  domain.TestSessionUsecase
	userRepo domain.UserRepository
}

func NewTestSessionHandler(usecase domain.TestSessionUsecase, userRepo domain.UserRepository) *TestSessionHandler {
	return &TestSessionHandler{usecase: usecase, userRepo: userRepo}
}

// CreateSession - POST /api/hr/test-sessions
func (h *TestSessionHandler) CreateSession(c *fiber.Ctx) error {
	var req domain.TestSessionCreateRequest

	// Parse request body
	if err := c.BodyParser(&req); err != nil {
		return response.BadRequest(
			c,
			"Invalid request body",
		)
	}

	// =========================
	// USER ID
	// =========================

	userIDStr, ok := c.Locals("user_id").(string)

	// fallback kalau tidak login/auth middleware mati
	if !ok || userIDStr == "" {
		// userIDStr = "0d879362-5f7c-4347-ad24-ceec0723938a"
		user, err := h.userRepo.GetByEmail(
			c.Context(),
			req.RecruiterEmail,
		)
		if err != nil {
			return response.NotFound(c, "User not found")
		}
		userIDStr = user.ID.String()
	}

	// =========================
	// COMPANY ID
	// =========================

	companyID := ctxval.GetCompanyID(c)

	if companyID == uuid.Nil {
		return response.NotFound(c, "Company not found")
	}

	req.CompanyID = companyID

	req.CreatedBy = uuid.MustParse(userIDStr)

	// =========================
	// DEBUG LOG
	// =========================

	log.Printf("Incoming Request: %+v\n", req)

	// =========================
	// CREATE SESSION
	// =========================

	resp, err := h.usecase.CreateSession(
		c.Context(),
		&req,
	)

	if err != nil {
		log.Printf("CreateSession Error: %v\n", err)

		return response.InternalError(
			c,
			err.Error(),
		)
	}

	// =========================
	// SUCCESS RESPONSE
	// =========================

	return response.Created(
		c,
		"Test session created successfully",
		resp,
	)
}

// GetSession - GET /api/hr/test-sessions/:id
func (h *TestSessionHandler) GetSession(c *fiber.Ctx) error {
	companyID := ctxval.GetCompanyID(c)
	id, err := uuid.Parse(c.Params("id"))
	if err != nil {
		return response.BadRequest(c, "Invalid session ID format")
	}

	resp, err := h.usecase.GetSession(c.Context(), id, companyID)
	if err != nil {
		return response.NotFound(c, err.Error())
	}

	return response.OK(c, "Success", resp)
}

// ListSessions - GET /api/hr/test-sessions
func (h *TestSessionHandler) ListSessions(c *fiber.Ctx) error {
	companyID := ctxval.GetCompanyID(c)
	limit, _ := strconv.Atoi(c.Query("limit", "10"))
	page, _ := strconv.Atoi(c.Query("page", "1"))

	sessions, total, err := h.usecase.ListSessions(c.Context(), companyID, limit, page)
	if err != nil {
		return response.InternalError(c, err.Error())
	}

	totalPage := total / limit
	if total%limit > 0 {
		totalPage++
	}

	return response.OK(c, "Success", sessions, response.PaginationMeta{
		CurrentPage: page,
		TotalPage:   totalPage,
		TotalItems:  int64(total),
		PerPage:     limit,
	})
}
