<?php
// Backfill deal_products from requested_services/title for non-legacy deals missing deal_products.

require __DIR__ . '/../../vendor/autoload.php';
$app = require __DIR__ . '/../../app/bootstrap.php';
$pdo = $app->db->getPdo();

$sql = "
    SELECT d.id, d.didar_deal_id, d.requested_services, d.title
    FROM deals d
    WHERE COALESCE(d.is_legacy_didar, 0) = 0
      AND NOT EXISTS (SELECT 1 FROM deal_products dp WHERE dp.deal_id = d.id)
      AND (
        (d.requested_services IS NOT NULL AND d.requested_services <> '' AND d.requested_services <> '[]')
        OR (d.title IS NOT NULL AND d.title <> '')
      )
";

$stmt = $pdo->query($sql);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

$updated = 0;
$noMatch = 0;

foreach ($rows as $row) {
    $dealKey = $row['didar_deal_id'] ?: (string)$row['id'];
    $requested = $row['requested_services'] ?? '';
    $title = $row['title'] ?? '';

    $matched = $app->services->deal->ensureDealProductsFromText($dealKey, $requested, $title);
    if (!empty($matched)) {
        $updated++;
        echo "Matched deal {$dealKey} -> products: " . implode(',', $matched) . PHP_EOL;
    } else {
        $noMatch++;
    }
}

$total = count($rows);
echo "Backfill complete. Total: {$total}, Updated: {$updated}, No match: {$noMatch}" . PHP_EOL;
