CREATE TABLE presenca_bank_clt_cases (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    lead_id INT UNSIGNED NOT NULL UNIQUE,
    integration_id INT UNSIGNED NOT NULL,
    loan_proposal_id INT UNSIGNED NULL,
    tracking_token CHAR(32) NOT NULL,
    borrower_name VARCHAR(150) NOT NULL,
    borrower_cpf VARCHAR(20) NOT NULL,
    borrower_email VARCHAR(150) NULL,
    borrower_phone VARCHAR(30) NULL,
    borrower_mother VARCHAR(150) NULL,
    borrower_birth_date DATE NULL,
    borrower_gender CHAR(1) NULL,
    borrower_marital_status VARCHAR(30) NULL,
    borrower_income DECIMAL(12,2) NULL,
    employment_employer_cnpj VARCHAR(20) NULL,
    employment_registration VARCHAR(60) NULL,
    employment_hiring_date DATE NULL,
    address_zip VARCHAR(15) NULL,
    address_state CHAR(2) NULL,
    address_city VARCHAR(100) NULL,
    address_district VARCHAR(100) NULL,
    address_street VARCHAR(150) NULL,
    address_number VARCHAR(20) NULL,
    address_complement VARCHAR(100) NULL,
    bank_code VARCHAR(10) NULL,
    bank_agency VARCHAR(10) NULL,
    bank_account VARCHAR(20) NULL,
    bank_account_digit VARCHAR(5) NULL,
    bank_account_type VARCHAR(20) NULL,
    bank_credit_method VARCHAR(10) NULL,
    auth_token TEXT NULL,
    auth_token_acquired_at DATETIME NULL,
    auth_token_expires_at DATETIME NULL,
    data_prev_term_id CHAR(36) NULL,
    data_prev_term_signed_at DATETIME NULL,
    vinculos_payload MEDIUMTEXT NULL,
    vinculos_last_synced_at DATETIME NULL,
    selected_employment_registration VARCHAR(60) NULL,
    margin_payload MEDIUMTEXT NULL,
    margin_last_synced_at DATETIME NULL,
    margin_amount DECIMAL(12,2) NULL,
    tables_payload MEDIUMTEXT NULL,
    tables_last_synced_at DATETIME NULL,
    selected_table_id VARCHAR(60) NULL,
    selected_installments SMALLINT NULL,
    selected_requested_value DECIMAL(12,2) NULL,
    selected_installment_value DECIMAL(12,2) NULL,
    operation_id VARCHAR(100) NULL,
    operation_status VARCHAR(60) NULL,
    operation_last_synced_at DATETIME NULL,
    operation_payload LONGTEXT NULL,
    webhook_last_payload LONGTEXT NULL,
    manual_followup_required TINYINT(1) NOT NULL DEFAULT 0,
    notes TEXT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
    CONSTRAINT fk_presenca_clt_lead FOREIGN KEY (lead_id) REFERENCES leads (id) ON DELETE CASCADE,
    CONSTRAINT fk_presenca_clt_integration FOREIGN KEY (integration_id) REFERENCES api_integrations (id) ON DELETE RESTRICT,
    CONSTRAINT fk_presenca_clt_proposal FOREIGN KEY (loan_proposal_id) REFERENCES loan_proposals (id) ON DELETE SET NULL,
    UNIQUE KEY idx_presenca_clt_tracking (tracking_token),
    INDEX idx_presenca_clt_borrower_cpf (borrower_cpf),
    INDEX idx_presenca_clt_operation (operation_id),
    INDEX idx_presenca_clt_integration (integration_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
