-- Tenants form and modal

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

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

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

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

INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 39, 'settings', 'settings', 'settings', (SELECT id FROM element_types WHERE name='textarea' LIMIT 1), 4
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 39 AND field_name = 'settings');

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

-- Tenants modal definition
INSERT INTO ui_modals (name, config, tenant_id, branch_id)
SELECT 'Tenants', '{"title":"Tenants","header":[{"type":"button","label":"Add Tenant","formName":"Tenant"}],"body":[{"type":"table","options":{"tableName":"tenants","showGlobalSearch":false,"addButton":false}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM ui_modals WHERE name = 'Tenants');

-- Update dashboard card permissions action slug
UPDATE ui_actions SET button_id='Tenants'
WHERE page='Dashboard' AND action_key='card_permissions' AND button_id='TenantAdmin';
