-- User form

-- Create User form if it doesn't exist
INSERT INTO forms (id, name, description, mapped_table, tenant_id, branch_id)
SELECT 41, 'User', 'User account details', 'users', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 41);

-- Form fields
INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 41, 'full_name', 'full_name', 'full_name', (SELECT id FROM element_types WHERE name='text' LIMIT 1), 1
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 41 AND field_name = 'full_name');

INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 41, 'email', 'emails', 'emails', (SELECT id FROM element_types WHERE name='text-multiple' LIMIT 1), 2
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 41 AND field_name = 'emails');

INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 41, 'password', 'password', 'password', (SELECT id FROM element_types WHERE name='text' LIMIT 1), 3
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 41 AND field_name = 'password');

INSERT INTO form_elements (
    form_id, label, field_name, data_column, type_id,
    options_table, options_label_column, options_value_column, order_index)
SELECT 41, 'tenant_id', 'tenant_id', 'tenant_id',
    (SELECT id FROM element_types WHERE name='dropdown' LIMIT 1),
    'tenants', 'name', 'id', 4
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 41 AND field_name = 'tenant_id');

INSERT INTO form_elements (
    form_id, label, field_name, data_column, type_id,
    options_table, options_label_column, options_value_column, order_index)
SELECT 41, 'groups', 'groups', 'groups',
    (SELECT id FROM element_types WHERE name='multiselect-search' LIMIT 1),
    'groups', 'name', 'id', 5
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 41 AND field_name = 'groups');

-- Default table view
INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
SELECT 41, 'Default', '["full_name","emails","tenant_id"]', 'full_name', 'ASC'
WHERE NOT EXISTS (SELECT 1 FROM table_views WHERE form_id = 41 AND name = 'Default');

