package job

import (
	"fmt"
	"path/filepath"

	"hyapp-admin-server/internal/config"
	"hyapp-admin-server/internal/modules/shared"
	"hyapp-admin-server/internal/repository"
	"hyapp-admin-server/internal/response"

	"github.com/gin-gonic/gin"
)

type Handler struct {
	service *JobService
	audit   shared.OperationLogger
}

func New(store *repository.Store, cfg config.Config, audit shared.OperationLogger) *Handler {
	return &Handler{service: NewService(store, cfg), audit: audit}
}

func (h *Handler) ListJobs(c *gin.Context) {
	options := shared.ListOptions(c)
	jobs, total, err := h.service.ListJobs(options)
	if err != nil {
		response.ServerError(c, "获取任务失败")
		return
	}
	response.OK(c, response.Page{Items: jobs, Page: options.Page, PageSize: options.PageSize, Total: total})
}

func (h *Handler) CreateUserExportJob(c *gin.Context) {
	job, err := h.service.CreateUserExportJob(shared.ActorFromContext(c), shared.ListOptions(c))
	if err != nil {
		response.ServerError(c, "创建导出任务失败")
		return
	}
	shared.OperationLog(c, h.audit, "create-user-export-job", "admin_jobs", "success", fmt.Sprintf("job_id=%d", job.ID))
	response.OK(c, job)
}

func (h *Handler) CancelJob(c *gin.Context) {
	id, ok := shared.ParseID(c, "id")
	if !ok {
		return
	}
	if err := h.service.CancelJob(id); err != nil {
		response.BadRequest(c, err.Error())
		return
	}
	shared.OperationLog(c, h.audit, "cancel-job", "admin_jobs", "success", fmt.Sprintf("job_id=%d", id))
	response.OK(c, gin.H{"canceled": true})
}

func (h *Handler) DownloadJobArtifact(c *gin.Context) {
	id, ok := shared.ParseID(c, "id")
	if !ok {
		return
	}
	_, artifactPath, err := h.service.JobArtifact(id)
	if err != nil {
		response.BadRequest(c, err.Error())
		return
	}
	shared.OperationLog(c, h.audit, "download-job-artifact", "admin_jobs", "success", fmt.Sprintf("job_id=%d", id))
	c.Header("Content-Disposition", "attachment; filename="+filepath.Base(artifactPath))
	c.File(artifactPath)
}
