// internal/controllers/report_controller.go
package controllers

import (
	"fmt"
	"lost-and-found/internal/models"
	"lost-and-found/internal/services"
	"lost-and-found/internal/utils"
	"net/http"
	"time"

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

type ReportController struct {
	exportService *services.ExportService
}

func NewReportController(db *gorm.DB) *ReportController {
	return &ReportController{
		exportService: services.NewExportService(db),
	}
}

// ExportReport exports report based on request
// POST /api/reports/export
func (c *ReportController) ExportReport(ctx *gin.Context) {
	userObj, _ := ctx.Get("user")
	user := userObj.(*models.User)

	var req services.ExportRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		utils.ErrorResponse(ctx, http.StatusBadRequest, "Invalid request data", err.Error())
		return
	}

	ipAddress := ctx.ClientIP()
	userAgent := ctx.Request.UserAgent()

	var buffer *[]byte
	var filename string
	var contentType string
	var err error

	// Generate report based on type and format
	switch req.Type {
	case "items":
		if req.Format == "pdf" {
			buf, e := c.exportService.ExportItemsToPDF(req, user.ID, ipAddress, userAgent)
			if e != nil {
				err = e
			} else {
				data := buf.Bytes()
				buffer = &data
				filename = fmt.Sprintf("items_report_%s.pdf", time.Now().Format("20060102"))
				contentType = "application/pdf"
			}
		} else {
			buf, e := c.exportService.ExportItemsToExcel(req, user.ID, ipAddress, userAgent)
			if e != nil {
				err = e
			} else {
				data := buf.Bytes()
				buffer = &data
				filename = fmt.Sprintf("items_report_%s.xlsx", time.Now().Format("20060102"))
				contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
			}
		}

	case "archives":
		buf, e := c.exportService.ExportArchivesToPDF(req, user.ID, ipAddress, userAgent)
		if e != nil {
			err = e
		} else {
			data := buf.Bytes()
			buffer = &data
			filename = fmt.Sprintf("archives_report_%s.pdf", time.Now().Format("20060102"))
			contentType = "application/pdf"
		}

	case "claims":
		buf, e := c.exportService.ExportClaimsToPDF(req, user.ID, ipAddress, userAgent)
		if e != nil {
			err = e
		} else {
			data := buf.Bytes()
			buffer = &data
			filename = fmt.Sprintf("claims_report_%s.pdf", time.Now().Format("20060102"))
			contentType = "application/pdf"
		}

	default:
		utils.ErrorResponse(ctx, http.StatusBadRequest, "Invalid report type", "")
		return
	}

	if err != nil {
		utils.ErrorResponse(ctx, http.StatusInternalServerError, "Failed to generate report", err.Error())
		return
	}

	// Set headers
	ctx.Header("Content-Type", contentType)
	ctx.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
	ctx.Header("Content-Length", fmt.Sprintf("%d", len(*buffer)))

	// Send file
	ctx.Data(http.StatusOK, contentType, *buffer)
}