-- Stage 0: Database Updates for Mobile Support & Bulk Import

-- 1. Update Users Table
ALTER TABLE users ADD COLUMN phone VARCHAR(20) NULL AFTER email;
ALTER TABLE users ADD COLUMN phone_hash VARCHAR(64) NULL AFTER phone;
ALTER TABLE users ADD COLUMN pin_hash VARCHAR(255) NULL;
ALTER TABLE users ADD COLUMN biometric_enabled BOOLEAN DEFAULT FALSE;
ALTER TABLE users ADD INDEX idx_phone_hash (phone_hash);

-- 2. User Devices Table
CREATE TABLE user_devices (
    id CHAR(36) PRIMARY KEY DEFAULT (UUID()),
    user_id CHAR(36) NOT NULL,
    device_fingerprint VARCHAR(64) NOT NULL,
    device_name VARCHAR(100),
    platform ENUM('android','ios') NOT NULL,
    app_version VARCHAR(20),
    push_token TEXT NULL,
    is_trusted BOOLEAN DEFAULT FALSE,
    last_seen_at DATETIME,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    UNIQUE KEY uq_user_device (user_id, device_fingerprint)
);

-- 3. Invoice Batches Table
CREATE TABLE invoice_batches (
    id CHAR(36) PRIMARY KEY,
    tenant_id CHAR(36) NOT NULL,
    company_id CHAR(36) NOT NULL,
    uploaded_by CHAR(36) NOT NULL,
    total_images INT NOT NULL DEFAULT 0,
    processed_images INT NOT NULL DEFAULT 0,
    status ENUM('uploading','processing','done','partial_fail') DEFAULT 'uploading',
    source ENUM('mobile_scan','web_upload','whatsapp') DEFAULT 'mobile_scan',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    completed_at DATETIME NULL,
    FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
    FOREIGN KEY (company_id) REFERENCES companies(id) ON DELETE CASCADE,
    FOREIGN KEY (uploaded_by) REFERENCES users(id) ON DELETE SET NULL
);

-- 4. Invoice Processing Queue Table
CREATE TABLE invoice_processing_queue (
    id INT AUTO_INCREMENT PRIMARY KEY,
    batch_id CHAR(36) NOT NULL,
    invoice_id CHAR(36) NULL,
    tenant_id CHAR(36) NOT NULL,
    image_path VARCHAR(500) NOT NULL,
    status ENUM('pending','processing','done','failed') DEFAULT 'pending',
    attempts INT DEFAULT 0,
    error_message TEXT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    processed_at DATETIME NULL,
    INDEX idx_status_tenant (status, tenant_id),
    INDEX idx_batch (batch_id)
);

-- 5. Excel Imports Table
CREATE TABLE excel_imports (
    id CHAR(36) PRIMARY KEY DEFAULT (UUID()),
    tenant_id CHAR(36) NOT NULL,
    company_id CHAR(36) NOT NULL,
    uploaded_by CHAR(36) NOT NULL,
    filename VARCHAR(255) NOT NULL,
    total_rows INT DEFAULT 0,
    success_rows INT DEFAULT 0,
    failed_rows INT DEFAULT 0,
    status ENUM('processing','done','failed') DEFAULT 'processing',
    error_log JSON NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
);
