-- Create lawyers table and modal

-- Table: lawyers
CREATE TABLE lawyers (
    id SERIAL,
    tenant_id INTEGER DEFAULT NULL,
    full_name VARCHAR(255) DEFAULT NULL,
    email VARCHAR(255) DEFAULT NULL,
    phone VARCHAR(50) DEFAULT NULL,
    date_joined DATE DEFAULT NULL,
    isDeleted BOOLEAN NOT NULL DEFAULT FALSE,
    updatedAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
);
CREATE INDEX lawyers_tenant_idx ON lawyers (tenant_id);

-- Lawyer form and modal
INSERT INTO forms (id, name, description, mapped_table, tenant_id, branch_id)
SELECT 37, 'Lawyer', 'Lawyer details', 'lawyers', NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM forms WHERE id = 37);

INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 37, 'full_name', 'full_name', 'full_name', 1, 1
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 37 AND field_name = 'full_name');
INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 37, 'email', 'email', 'email', 1, 2
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 37 AND field_name = 'email');
INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 37, 'phone', 'phone', 'phone', 1, 3
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 37 AND field_name = 'phone');
INSERT INTO form_elements (form_id, label, field_name, data_column, type_id, order_index)
SELECT 37, 'date_joined', 'date_joined', 'date_joined', 3, 4
WHERE NOT EXISTS (SELECT 1 FROM form_elements WHERE form_id = 37 AND field_name = 'date_joined');

INSERT INTO table_views (form_id, name, columns, sort_by, sort_dir)
SELECT 37, 'Default', '["full_name","email","phone","date_joined"]', 'full_name', 'ASC'
WHERE NOT EXISTS (SELECT 1 FROM table_views WHERE form_id = 37 AND name = 'Default');

INSERT INTO ui_modals (name, config, tenant_id, branch_id)
SELECT 'Lawyers', '{"title":"Lawyers","header":[{"type":"button","label":"Add Lawyer","formName":"Lawyer"},{"type":"button","label":"Detail View","onClick":"openSelectedDetail"}],"body":[{"type":"table","options":{"tableName":"lawyers","showGlobalSearch":false,"addButton":false,"rowClick":"selectRecord"}}],"footer":[{"type":"button","label":"Close","onClick":"closeModal"}]}' , NULL, NULL
WHERE NOT EXISTS (SELECT 1 FROM ui_modals WHERE name = 'Lawyers');
