package job

import (
	"fmt"
	"os"
	"path/filepath"
	"system-altrak/pkg/utils"

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

type Handler struct {
	service JobService
}

func NewHandler(s JobService) *Handler {
	return &Handler{service: s}
}

func (h *Handler) GetActiveJobs(c *fiber.Ctx) error {
	branchID, _ := c.Locals("current_branch_id").(uint)
	jobs, err := h.service.GetActiveJobs(branchID)
	if err != nil {
		return utils.InternalErrorResponse(c, "Failed to retrieve active intelligence tasks")
	}
	return utils.SuccessResponse(c, "Active background tasks synchronized", jobs)
}

func (h *Handler) ListHistoricalJobs(c *fiber.Ctx) error {
	branchID, _ := c.Locals("current_branch_id").(uint)
	page := c.QueryInt("page", 1)
	limit := c.QueryInt("limit", 20)

	jobs, total, err := h.service.ListJobs(page, limit, branchID)
	if err != nil {
		return utils.InternalErrorResponse(c, "Failed to aggregate task history")
	}

	pagination, _ := utils.NewPagination(page, limit, total)
	pagination.SetData(jobs)

	return utils.PaginatedSuccessResponse(c, "Intelligence Task Ledger", jobs, pagination.GetMeta())
}

func (h *Handler) DownloadJobFile(c *fiber.Ctx) error {
	id, err := utils.ParseParamID(c, "id")
	if err != nil {
		return utils.ErrorResponse(c, fiber.StatusBadRequest, "Invalid ID parameter")
	}

	job, err := h.service.GetJobByID(id)
	if err != nil {
		return utils.NotFoundResponse(c, "Job")
	}

	if job.Status != "COMPLETED" {
		return utils.ErrorResponse(c, fiber.StatusBadRequest, "Job has not completed yet")
	}

	var ext string
	var contentType string
	if job.JobType == "EXPORT_EXCEL" {
		ext = ".xlsx"
		contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
	} else if job.JobType == "EXPORT_PDF" {
		ext = ".pdf"
		contentType = "application/pdf"
	} else {
		return utils.ErrorResponse(c, fiber.StatusBadRequest, "Job type does not support file download")
	}

	filePath := filepath.Join("./backups/exports", fmt.Sprintf("job_%d%s", job.ID, ext))
	if _, err := os.Stat(filePath); os.IsNotExist(err) {
		return utils.NotFoundResponse(c, "Export file")
	}

	c.Set("Content-Type", contentType)
	c.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="Export-%s%s"`, job.JobType, ext))
	return c.SendFile(filePath)
}
