package handler

import (
	"apskel-pos-be/internal/appcontext"
	"apskel-pos-be/internal/contract"
	"apskel-pos-be/internal/service"
	"apskel-pos-be/internal/util"
	"time"

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

type ReportHandler struct {
	reportService service.ReportService
	userService   UserService
}

func NewReportHandler(reportService service.ReportService, userService UserService) *ReportHandler {
	return &ReportHandler{reportService: reportService, userService: userService}
}

func (h *ReportHandler) GetDailyTransactionReportPDF(c *gin.Context) {
	ctx := c.Request.Context()
	ci := appcontext.FromGinContext(ctx)

	outletID := c.Param("outlet_id")
	var dayPtr *time.Time
	if d := c.Query("date"); d != "" {
		if t, err := time.Parse("2006-01-02", d); err == nil {
			dayPtr = &t
		}
	}

	user, err := h.userService.GetUserByID(ctx, ci.UserID)
	var genBy string
	if err != nil {
		genBy = ci.UserID.String()
	} else {
		genBy = user.Name
	}

	publicURL, fileName, err := h.reportService.GenerateDailyTransactionPDF(ctx, ci.OrganizationID.String(), outletID, dayPtr, genBy)
	if err != nil {
		util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{contract.NewResponseError("internal_error", "ReportHandler::GetDailyTransactionReportPDF", err.Error())}), "ReportHandler::GetDailyTransactionReportPDF")
		return
	}

	util.HandleResponse(c.Writer, c.Request, contract.BuildSuccessResponse(map[string]string{
		"url":       publicURL,
		"file_name": fileName,
	}), "ReportHandler::GetDailyTransactionReportPDF")
}
