package api

import (
	"database/sql"
	"net/http"
	"os"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"

	"github.com/rycroftapparel/workpulse-api/internal/httpapi"
)

// deleteReport removes a report. Superadmin may delete any report; owner may delete own draft only.
func (s *Server) deleteReport(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, httpapi.Fail("validation", "invalid id"))
		return
	}

	ctx, cancel := s.ctx(c)
	defer cancel()
	uid := userID(c)
	super := roleIsSuperadmin(c)

	var owner uint64
	var status string
	err = s.DB.QueryRowContext(ctx, `SELECT user_id, status FROM reports WHERE id = $1`, id).Scan(&owner, &status)
	if err == sql.ErrNoRows {
		c.JSON(http.StatusNotFound, httpapi.Fail("not_found", "report not found"))
		return
	}
	if err != nil {
		c.JSON(http.StatusInternalServerError, httpapi.Fail("db", err.Error()))
		return
	}

	if super {
		// allowed
	} else if owner == uid && strings.ToLower(strings.TrimSpace(status)) == "draft" {
		// allowed
	} else if owner == uid {
		c.JSON(http.StatusForbidden, httpapi.Fail("forbidden", "Hanya draf milik Anda yang dapat dihapus."))
		return
	} else {
		c.JSON(http.StatusForbidden, httpapi.Fail("forbidden", "cannot delete this report"))
		return
	}

	s.removeAllReportUploadFiles(id)

	if _, err := s.DB.ExecContext(ctx, `DELETE FROM reports WHERE id = $1`, id); err != nil {
		c.JSON(http.StatusInternalServerError, httpapi.Fail("db", err.Error()))
		return
	}

	s.Hub.BroadcastEvent("report.deleted", gin.H{"id": id})
	s.recordUserActivity(c, ctx, uid, "report.deleted", "Daily report deleted", "", gin.H{"reportId": id})
	c.JSON(http.StatusOK, httpapi.OK(gin.H{"id": id}))
}

func (s *Server) removeAllReportUploadFiles(reportID uint64) {
	_ = os.RemoveAll(s.reportAttachmentsDir(reportID))
}
