WITH seed_product AS (
    SELECT
        'BMCnet Statisk WAN IP'::TEXT AS name,
        'Statisk offentlig WAN IPv4-adresse'::TEXT AS short_description,
        'service'::TEXT AS type,
        'monthly'::TEXT AS billing_period,
        0.00::DECIMAL(10,2) AS sales_price,
        jsonb_build_object(
            'network',
            jsonb_build_object(
                'kind', 'ip_allocation',
                'ip_prefix_length', 32
            )
        ) AS attributes_json
),
updated AS (
    UPDATE products p
    SET short_description = s.short_description,
        type = COALESCE(NULLIF(p.type, ''), s.type),
        billing_period = COALESCE(NULLIF(p.billing_period, ''), s.billing_period),
        sales_price = COALESCE(p.sales_price, s.sales_price),
        status = 'active',
        billable = true,
        attributes_json = COALESCE(p.attributes_json, '{}'::jsonb) || s.attributes_json,
        updated_at = CURRENT_TIMESTAMP
    FROM seed_product s
    WHERE p.deleted_at IS NULL
      AND LOWER(p.name) = LOWER(s.name)
    RETURNING p.id
)
INSERT INTO products (
    name,
    short_description,
    type,
    status,
    sales_price,
    vat_rate,
    billing_period,
    billable,
    attributes_json
)
SELECT
    s.name,
    s.short_description,
    s.type,
    'active',
    s.sales_price,
    25.00,
    s.billing_period,
    true,
    s.attributes_json
FROM seed_product s
WHERE NOT EXISTS (
    SELECT 1
    FROM products p
    WHERE p.deleted_at IS NULL
      AND LOWER(p.name) = LOWER(s.name)
);
