<?php

declare(strict_types=1);

require_once __DIR__.'/../vendor/autoload.php';

use Doctrine\DBAL\DriverManager;

$conn = DriverManager::getConnection([
    'driver' => 'pdo_pgsql',
    'host' => 'localhost',
    'port' => 5432,
    'dbname' => 'inventory',
    'user' => 'ferme_user',
    'password' => 'fermerecette',
]);

echo "--- ModelTypes with orphaned piece values (CFs lost) ---\n\n";
$rows = $conn->fetchAllAssociative("
    SELECT mt.id, mt.name, mt.category,
           cf_orphan.name as lost_field,
           COUNT(*) as affected_pieces,
           COUNT(*) FILTER (WHERE cfv.value != '' AND cfv.value IS NOT NULL) as with_data
    FROM custom_field_values cfv
    JOIN custom_fields cf_orphan ON cf_orphan.id = cfv.customfieldid
    JOIN pieces p ON p.id = cfv.pieceid
    JOIN model_types mt ON mt.id = p.typepieceid
    WHERE cf_orphan.typecomposantid IS NULL
      AND cf_orphan.typepieceid IS NULL
      AND cf_orphan.typeproductid IS NULL
    GROUP BY mt.id, mt.name, mt.category, cf_orphan.name
    ORDER BY mt.name, cf_orphan.name
");

foreach ($rows as $r) {
    $status = $r['with_data'] > 0 ? 'HAS DATA' : 'empty';
    echo sprintf("  ModelType '%s' | field '%s' | %d pieces (%d with data) [%s]\n",
        $r['name'], $r['lost_field'], $r['affected_pieces'], $r['with_data'], $status);
}

echo sprintf("\nTotal: %d ModelType/field combinations\n", count($rows));

// Check if these fields exist on the current ModelType
echo "\n--- Current CFs on these ModelTypes ---\n\n";
$mtIds = array_unique(array_column($rows, 'id'));
foreach ($mtIds as $mtId) {
    $mtName = $conn->fetchOne("SELECT name FROM model_types WHERE id = ?", [$mtId]);
    $currentCfs = $conn->fetchAllAssociative(
        "SELECT name FROM custom_fields WHERE typepieceid = ? ORDER BY orderindex",
        [$mtId]
    );
    $cfNames = array_column($currentCfs, 'name');
    echo sprintf("  '%s': %s\n", $mtName, $cfNames ? implode(', ', $cfNames) : '(aucun CF)');
}
