package distribution

import (
	"context"

	"github.com/TaruLab/keluargamart-backend/internal/db"
	"mime/multipart"
	"strings"
)

// PODSaver stores a parsed multipart proof-of-delivery photo and returns the
// /uploads/ path it was served under. Wired from cmd/server onto the same
// uploads pipeline payment proofs and buyer received-proofs use (same 5 MB
// cap, same image-type allowlist, same opaque keys), so every handover photo
// shares one storage policy. It takes the parsed header rather than a raw
// reader because the photo rides the DO completion request together with
// other form fields — re-wrapping bytes into a synthetic multipart request
// just to reuse the storage rules would be complexity for nothing.
type PODSaver func(ctx context.Context, header *multipart.FileHeader) (string, error)

// WithPODSaver wires the POD storage seam (called from main). Without it a DO
// still completes, but an attached photo fails loudly instead of being
// silently dropped — losing evidence quietly is worse than refusing it.
func (s *Service) WithPODSaver(fn PODSaver) *Service {
	s.podSaver = fn
	return s
}

// SetDeliveryOrderPOD stores the POD photo (when one was attached) and writes
// both POD columns onto the CALLER's transaction (q). It used to pass nil as
// the tx, so every DO completion — with or without a photo — panicked in
// q.Exec and the endpoint answered 500.
func (s *Service) SetDeliveryOrderPOD(ctx context.Context, q db.DBTX, doID int64, photo *multipart.FileHeader, recipient string) error {
	var url *string
	if photo != nil {
		if s.podSaver == nil {
			return ErrPODSaverNotWired
		}
		stored, err := s.podSaver(ctx, photo)
		if err != nil {
			return err
		}
		if !strings.HasPrefix(stored, "/uploads/") {
			return ErrPODURLInvalid
		}
		url = &stored
	}
	return s.store.SetDeliveryOrderPODRow(ctx, q, doID, url, recipient)
}
