UPDATE tax_rates
SET rate = 20, name = 'TVA 20%', is_active = 1
WHERE name = 'TVA 20%';

INSERT INTO tax_rates (company_id, name, rate, is_default, is_active)
SELECT c.id, 'TVA 20%', 20, 1, 1
FROM companies c
WHERE NOT EXISTS (
    SELECT 1 FROM tax_rates t WHERE t.company_id = c.id AND t.rate = 20
);

UPDATE tax_rates SET is_default = 0;

UPDATE tax_rates t
JOIN (
    SELECT company_id, MIN(id) AS id
    FROM tax_rates
    WHERE rate = 20
    GROUP BY company_id
) selected ON selected.id = t.id
SET t.rate = 20, t.is_default = 1, t.is_active = 1;

UPDATE products p
JOIN (
    SELECT company_id, MIN(id) AS id
    FROM tax_rates
    WHERE rate = 20
    GROUP BY company_id
) selected ON selected.company_id = p.company_id
SET p.tax_rate_id = selected.id;

DELETE t
FROM tax_rates t
LEFT JOIN products p ON p.tax_rate_id = t.id
WHERE t.rate <> 20 AND p.id IS NULL;

DELETE duplicate_rate
FROM tax_rates duplicate_rate
JOIN (
    SELECT company_id, MIN(id) AS keep_id
    FROM tax_rates
    WHERE rate = 20
    GROUP BY company_id
) selected ON selected.company_id = duplicate_rate.company_id
WHERE duplicate_rate.rate = 20 AND duplicate_rate.id <> selected.keep_id;
