-- ============================================================================
-- Kivitendo: m3 -> m³ ändern (für ZUGFeRD-Kompatibilität)
-- ============================================================================

BEGIN;

-- Constraints temporär entfernen
ALTER TABLE assortment_items DROP CONSTRAINT IF EXISTS assortment_items_unit_fkey;
ALTER TABLE delivery_order_items DROP CONSTRAINT IF EXISTS delivery_order_items_unit_fkey;
ALTER TABLE invoice DROP CONSTRAINT IF EXISTS invoice_unit_fkey;
ALTER TABLE orderitems DROP CONSTRAINT IF EXISTS orderitems_unit_fkey;
ALTER TABLE parts DROP CONSTRAINT IF EXISTS parts_unit_fkey;
ALTER TABLE units_language DROP CONSTRAINT IF EXISTS units_language_unit_fkey;

-- ALLE Tabellen updaten: m3 -> m³
UPDATE units SET name = 'm³' WHERE name = 'm3';
UPDATE parts SET unit = 'm³' WHERE unit = 'm3';
UPDATE invoice SET unit = 'm³' WHERE unit = 'm3';
UPDATE orderitems SET unit = 'm³' WHERE unit = 'm3';
UPDATE delivery_order_items SET unit = 'm³' WHERE unit = 'm3';
UPDATE units_language SET unit = 'm³' WHERE unit = 'm3';

-- Constraints wieder hinzufügen
ALTER TABLE assortment_items ADD CONSTRAINT assortment_items_unit_fkey 
  FOREIGN KEY (unit) REFERENCES units(name);
ALTER TABLE delivery_order_items ADD CONSTRAINT delivery_order_items_unit_fkey 
  FOREIGN KEY (unit) REFERENCES units(name);
ALTER TABLE invoice ADD CONSTRAINT invoice_unit_fkey 
  FOREIGN KEY (unit) REFERENCES units(name);
ALTER TABLE orderitems ADD CONSTRAINT orderitems_unit_fkey 
  FOREIGN KEY (unit) REFERENCES units(name);
ALTER TABLE parts ADD CONSTRAINT parts_unit_fkey 
  FOREIGN KEY (unit) REFERENCES units(name);
ALTER TABLE units_language ADD CONSTRAINT units_language_unit_fkey 
  FOREIGN KEY (unit) REFERENCES units(name);

-- Ergebnis anzeigen
SELECT 'Fertig! m3 -> m³ geändert' as status;
SELECT 'Artikel:' as tabelle, COUNT(*) as anzahl FROM parts WHERE unit = 'm³'
UNION ALL
SELECT 'Rechnungen:', COUNT(*) FROM invoice WHERE unit = 'm³'
UNION ALL
SELECT 'Aufträge:', COUNT(*) FROM orderitems WHERE unit = 'm³';

SELECT 'Alle Einheiten:' as info;
SELECT name FROM units ORDER BY sortkey;

COMMIT;
