package sync

import (
	"fmt"
	"log/slog"
	"time"
)

// SeenPartnumber represents an unresolved vendor partnumber to report.
type SeenPartnumber struct {
	Partnumber  string
	Description string
	Ignored     bool
}

// PushPartnumberSeen inserts unresolved vendor partnumbers into qt_vendor_partnumber_seen on MariaDB.
// Existing rows are left untouched: no updates to last_seen_at, is_ignored, or description.
func (s *Service) PushPartnumberSeen(items []SeenPartnumber) error {
	if len(items) == 0 {
		return nil
	}

	mariaDB, err := s.getDB()
	if err != nil {
		return fmt.Errorf("database not available: %w", err)
	}

	now := time.Now().UTC()
	for _, item := range items {
		if item.Partnumber == "" {
			continue
		}
		err := mariaDB.Exec(`
			INSERT INTO qt_vendor_partnumber_seen
				(source_type, vendor, partnumber, description, is_ignored, last_seen_at)
			VALUES
				('manual', '', ?, ?, ?, ?)
			ON DUPLICATE KEY UPDATE
				partnumber = partnumber
		`, item.Partnumber, item.Description, item.Ignored, now).Error
		if err != nil {
			slog.Error("failed to insert partnumber_seen", "partnumber", item.Partnumber, "error", err)
			// Continue with remaining items
		}
	}

	slog.Info("partnumber_seen pushed to server", "count", len(items))
	return nil
}
