-- Suppliers get a structured address (street/city/postal_code/country) like
-- customers; the single free-text `address` blob is dropped. Existing data is
-- split best-effort: newlines normalized to ", ", first comma segment ->
-- street, the PSC (3+2 digits) -> postal_code, the remainder -> city.
-- Unparseable one-segment addresses keep their full text in `street`.

-- AlterTable: add the structured columns
ALTER TABLE `sklad_suppliers`
  ADD COLUMN `street` VARCHAR(255) NULL AFTER `phone`,
  ADD COLUMN `city` VARCHAR(255) NULL AFTER `street`,
  ADD COLUMN `postal_code` VARCHAR(20) NULL AFTER `city`,
  ADD COLUMN `country` VARCHAR(100) NULL AFTER `postal_code`;

-- Preserve data: best-effort split of the legacy free-text address
UPDATE `sklad_suppliers`
SET
  `street` = NULLIF(TRIM(SUBSTRING_INDEX(REPLACE(REPLACE(`address`, '\r', ''), '\n', ', '), ',', 1)), ''),
  `postal_code` = REGEXP_SUBSTR(`address`, '[0-9]{3}[ ]?[0-9]{2}'),
  `city` = NULLIF(TRIM(BOTH ',' FROM TRIM(REGEXP_REPLACE(
      SUBSTRING(
        REPLACE(REPLACE(`address`, '\r', ''), '\n', ', '),
        CHAR_LENGTH(SUBSTRING_INDEX(REPLACE(REPLACE(`address`, '\r', ''), '\n', ', '), ',', 1)) + 2
      ),
      '[0-9]{3}[ ]?[0-9]{2}', ''))), '')
WHERE `address` IS NOT NULL AND `address` <> '';

-- AlterTable: drop the legacy blob
ALTER TABLE `sklad_suppliers` DROP COLUMN `address`;
