-- +goose Up

CREATE TABLE units (
    code       VARCHAR(20) PRIMARY KEY,
    sort_order SMALLINT    NOT NULL DEFAULT 0
);
INSERT INTO units (code, sort_order) VALUES
    ('g',    1),
    ('kg',   2),
    ('ml',   3),
    ('l',    4),
    ('pcs',  5),
    ('pack', 6);

CREATE TABLE unit_translations (
    unit_code  VARCHAR(20) NOT NULL REFERENCES units(code) ON DELETE CASCADE,
    lang       VARCHAR(10) NOT NULL,
    name       TEXT        NOT NULL,
    PRIMARY KEY (unit_code, lang)
);
INSERT INTO unit_translations (unit_code, lang, name) VALUES
    ('g',    'ru', 'г'),
    ('kg',   'ru', 'кг'),
    ('ml',   'ru', 'мл'),
    ('l',    'ru', 'л'),
    ('pcs',  'ru', 'шт'),
    ('pack', 'ru', 'уп');

-- Normalize products.unit from Russian display strings to English codes
UPDATE products SET unit = 'g'    WHERE unit = 'г';
UPDATE products SET unit = 'kg'   WHERE unit = 'кг';
UPDATE products SET unit = 'ml'   WHERE unit = 'мл';
UPDATE products SET unit = 'l'    WHERE unit = 'л';
UPDATE products SET unit = 'pcs'  WHERE unit = 'шт';
UPDATE products SET unit = 'pack' WHERE unit = 'уп';
-- Normalize any remaining unknown values
UPDATE products SET unit = 'pcs' WHERE unit NOT IN (SELECT code FROM units);

-- Nullify unknown default_unit values in ingredient_mappings before adding FK
UPDATE ingredient_mappings
    SET default_unit = NULL
    WHERE default_unit IS NOT NULL
      AND default_unit NOT IN (SELECT code FROM units);

-- Foreign key constraints
ALTER TABLE products
    ADD CONSTRAINT fk_product_unit
    FOREIGN KEY (unit) REFERENCES units(code);

ALTER TABLE ingredient_mappings
    ADD CONSTRAINT fk_default_unit
    FOREIGN KEY (default_unit) REFERENCES units(code);

-- +goose Down
ALTER TABLE ingredient_mappings DROP CONSTRAINT IF EXISTS fk_default_unit;
ALTER TABLE products             DROP CONSTRAINT IF EXISTS fk_product_unit;
DROP TABLE IF EXISTS unit_translations;
DROP TABLE IF EXISTS units;
