-- Audit follow-up: 0024 only normalized rows that contained a literal
-- hyphen (`A-01`), but the audit caught that legacy NocoDB exports also
-- produced un-hyphenated padded forms (`A01`). Those rows skipped the
-- 0024 rewrite and remained non-canonical, which would break the public
-- /berths/:mooringNumber lookup (the route gates on `^[A-Z]+\d+$`).
--
-- This migration re-runs the rewrite with a WHERE clause broadened to
-- catch BOTH variants:
--   - hyphenated padded   ("A-01")  ← redundant after 0024 but harmless
--   - un-hyphenated padded ("A01")
-- Rows already in canonical form skip the UPDATE because the regex_replace
-- output equals the input AND the WHERE filter excludes them via the
-- "leading zero or hyphen" pattern.
UPDATE berths
SET mooring_number = regexp_replace(mooring_number, '^([A-Z]+)-?0*(\d+)$', '\1\2')
WHERE mooring_number ~ '^[A-Z]+-?0*\d+$'
  AND mooring_number !~ '^[A-Z]+\d+$';

DO $$
DECLARE
  bad_count integer;
BEGIN
  SELECT count(*) INTO bad_count
  FROM berths
  WHERE mooring_number !~ '^[A-Z]+\d+$';
  IF bad_count > 0 THEN
    RAISE NOTICE 'Post-rewrite: % rows still do not match ^[A-Z]+\d+$ - manual review needed', bad_count;
  END IF;
END $$;
