package handlers

import (
	"encoding/json"
	"fmt"

	"github.com/breakpilot/ai-compliance-sdk/internal/dsms"
	"github.com/breakpilot/ai-compliance-sdk/internal/iace"
	"github.com/breakpilot/ai-compliance-sdk/internal/rbac"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

// archiveTechFile stores a tech-file export to DSMS (best-effort, non-blocking)
// AND records the resulting CID in the IACE audit trail so the export is
// traceable. The "new_values" JSON carries the CID + filename so the audit
// timeline can later resolve the CID against the DSMS gateway for verify.
//
// Side-effect: when the archive succeeds, X-DSMS-CID / X-DSMS-Filename /
// X-DSMS-Size response headers are attached so the frontend can render an
// inline CID-badge directly in the export-success path (no separate audit
// query needed). Headers are written before c.Data() and survive the binary
// blob response.
func (h *IACEHandler) archiveTechFile(c *gin.Context, data []byte, filename string, projectID uuid.UUID) {
	result := dsms.Archive(data, filename, "ce_techfile", projectID.String(), "1")
	if result == nil || result.CID == "" {
		return
	}

	setDSMSResponseHeaders(c, result.CID, filename, result.Size)

	if h.store == nil {
		return
	}
	payload := map[string]string{
		"cid":      result.CID,
		"filename": filename,
		"size":     fmt.Sprintf("%d", result.Size),
	}
	newValues, _ := json.Marshal(payload)
	userID := rbac.GetUserID(c)
	_ = h.store.AddAuditEntry(
		c.Request.Context(),
		projectID,
		"tech_file_export",
		projectID,
		iace.AuditActionCreate,
		userID.String(),
		nil,
		newValues,
	)
}

// setDSMSResponseHeaders attaches the X-DSMS-* headers so the frontend can
// surface the archived CID inline (export-success badge) without re-querying
// the audit trail. Pure helper — no store, no side effects beyond headers.
func setDSMSResponseHeaders(c *gin.Context, cid, filename string, size int) {
	if cid == "" {
		return
	}
	c.Header("X-DSMS-CID", cid)
	c.Header("X-DSMS-Filename", filename)
	c.Header("X-DSMS-Size", fmt.Sprintf("%d", size))
	c.Header("Access-Control-Expose-Headers", "X-DSMS-CID, X-DSMS-Filename, X-DSMS-Size")
}
