-- Migrate legacy incident custom fields to Form Builder

INSERT INTO forms (id, name, description, mapped_table, tenant_id, branch_id)
SELECT 4, 'OHS Incident', 'Default incident report form', 'ohs_incidents', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 4);

-- migrate custom fields
INSERT INTO form_elements (form_id, tenant_id, branch_id, label, field_name, data_column, type_id, is_required)
SELECT 4, tenant_id, branch_id, field_name, field_name, field_name,
       COALESCE((SELECT id FROM element_types WHERE name = lower(field_type) LIMIT 1),
                (SELECT id FROM element_types WHERE name = 'text' LIMIT 1)),
       is_required
FROM ohs_incident_custom_fields
WHERE isDeleted = 0;
