<?php
// Seed products table from allowed_services lookup items if missing.

require __DIR__ . '/../../vendor/autoload.php';
$app = require __DIR__ . '/../../app/bootstrap.php';

$lookupItems = $app->repositories->lookup->getItemsByGroupCode('allowed_services', true);
$existingProducts = $app->repositories->product->all();

$existingNames = [];
foreach ($existingProducts as $product) {
    $name = trim((string)($product->name ?? ''));
    if ($name !== '') {
        $existingNames[mb_strtolower($name, 'UTF-8')] = true;
    }
}

$inserted = 0;
$skipped = 0;

foreach ($lookupItems as $item) {
    $name = trim((string)($item['value'] ?? $item['title'] ?? ''));
    if ($name === '') {
        continue;
    }
    $key = mb_strtolower($name, 'UTF-8');
    if (isset($existingNames[$key])) {
        $skipped++;
        continue;
    }

    $app->repositories->product->create($name);
    $existingNames[$key] = true;
    $inserted++;
    echo "Inserted product: {$name}" . PHP_EOL;
}

echo "Seed complete. Inserted: {$inserted}, Skipped: {$skipped}" . PHP_EOL;
