# noinspection SpellCheckingInspectionForFile

DELETE FROM storage_type WHERE legacyId IS NOT NULL;

INSERT INTO storage_type (
    legacyId,
    legacySlug,
    legacyPicture,
    createdAt,
    updatedAt,
    name,
    icon,
    lead,
    body
)
SELECT
    n.nid AS legacyId,
    SUBSTRING_INDEX( ua.alias, '/', -1 ) AS legacySlug,
    IF( COUNT( fm.fid ) = 0, NULL, JSON_ARRAYAGG(
        JSON_OBJECT(
            'id', fm.fid,
            'name', fm.filename,
            'uri', fm.uri,
            'mime', fm.filemime,
            'size', fm.filesize,
            'timestamp', fm.timestamp,
            'alt', fi.field_image_alt,
            'width', fi.field_image_width,
            'height', fi.field_image_height
        )
    ) ) AS legacyPicture,
    FROM_UNIXTIME( n.created ) AS createdAt,
    FROM_UNIXTIME( n.changed ) AS updatedAt,
    n.title AS name,
    CASE n.title
        WHEN 'Kültéri tengeri konténer' THEN 'container-storage'
        WHEN 'Beltéri temperált tároló' THEN 'warehouse'
        WHEN 'Kültéri nyitott parkoló' THEN 'square-parking'
        WHEN 'Gumiraktár' THEN 'tire'
        WHEN 'Iratraktár' THEN 'books'
        WHEN 'Bortrezor' THEN 'wine-bottle'
        WHEN 'Autótárolás' THEN 'garage-car'
    END AS icon,
    REGEXP_REPLACE( b.body_summary, '<[^>]+>', '' ) AS lead,
    b.body_value AS body
FROM raktar24_old.node AS n
JOIN raktar24_old.field_data_body AS b ON n.nid = b.entity_id AND b.bundle = 'tarolotipus'
LEFT JOIN raktar24_old.url_alias AS ua ON ua.source = CONCAT('node/', n.nid)
LEFT JOIN raktar24_old.file_usage AS fu ON n.nid = fu.id AND fu.type = 'node' AND fu.module = 'file'
LEFT JOIN raktar24_old.file_managed AS fm ON fu.fid = fm.fid
LEFT JOIN raktar24_old.field_data_field_image AS fi ON n.nid = fi.entity_id AND fu.fid = fi.field_image_fid AND fi.bundle = 'tarolotipus'
WHERE n.type = 'tarolotipus'
GROUP BY n.nid;