-- ════════════════════════════════════════════════════════════
-- مُصادَق — Comprehensive Phase 1 Migration
-- Tables for AI Extraction, JoFotara Integration, and Usage Logs
-- ════════════════════════════════════════════════════════════

-- 1. Invoice Line Items (For AI extracted data)
CREATE TABLE IF NOT EXISTS invoice_lines (
    id              CHAR(36) PRIMARY KEY DEFAULT (UUID()),
    invoice_id      CHAR(36) NOT NULL,
    line_number     INT NOT NULL,
    description     VARCHAR(255) NOT NULL,
    quantity        DECIMAL(10,3) DEFAULT 1,
    unit_price      DECIMAL(15,4) NOT NULL,
    tax_rate        DECIMAL(5,2) DEFAULT 16.00,
    tax_amount      DECIMAL(15,4) DEFAULT 0,
    discount        DECIMAL(15,4) DEFAULT 0,
    total_amount    DECIMAL(15,4) NOT NULL,
    created_at      DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_invoice (invoice_id),
    FOREIGN KEY (invoice_id) REFERENCES invoices(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 2. JoFotara Submissions Log
CREATE TABLE IF NOT EXISTS jofotara_submissions (
    id              CHAR(36) PRIMARY KEY DEFAULT (UUID()),
    invoice_id      CHAR(36) NOT NULL,
    tenant_id       CHAR(36) NOT NULL,
    company_id      CHAR(36) NOT NULL,
    jofotara_uuid   VARCHAR(100) NULL,
    xml_content     LONGTEXT NULL,
    status          ENUM('accepted', 'rejected', 'pending') DEFAULT 'pending',
    qr_code_raw     TEXT NULL, -- Base64 QR from JoFotara
    response_body   JSON NULL,
    submitted_at    DATETIME NULL,
    created_at      DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_invoice (invoice_id),
    INDEX idx_tenant (tenant_id),
    FOREIGN KEY (invoice_id) REFERENCES invoices(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 3. Update Companies for JoFotara Credentials
ALTER TABLE companies 
ADD COLUMN IF NOT EXISTS jofotara_client_id VARCHAR(255) NULL AFTER tax_identification_number,
ADD COLUMN IF NOT EXISTS jofotara_secret_key VARCHAR(255) NULL AFTER jofotara_client_id,
ADD COLUMN IF NOT EXISTS jofotara_status ENUM('active', 'inactive', 'pending') DEFAULT 'inactive' AFTER jofotara_secret_key;

-- 4. Update Invoices for AI and JoFotara metadata
ALTER TABLE invoices
ADD COLUMN IF NOT EXISTS invoice_category ENUM('simplified', 'standard') DEFAULT 'simplified' AFTER invoice_type,
ADD COLUMN IF NOT EXISTS ubl_type_code VARCHAR(10) DEFAULT '388' AFTER invoice_category,
ADD COLUMN IF NOT EXISTS payment_method_code VARCHAR(10) DEFAULT '013' AFTER ubl_type_code,
ADD COLUMN IF NOT EXISTS validation_warnings JSON NULL AFTER qr_code,
ADD COLUMN IF NOT EXISTS ai_confidence DECIMAL(5,2) DEFAULT 0 AFTER validation_warnings,
ADD COLUMN IF NOT EXISTS jofotara_uuid VARCHAR(100) NULL AFTER status;

-- 5. AI Usage Log (Cost & Token tracking)
CREATE TABLE IF NOT EXISTS ai_usage_log (
    id              INT AUTO_INCREMENT PRIMARY KEY,
    tenant_id       CHAR(36) NOT NULL,
    user_id         CHAR(36) NULL,
    company_id      CHAR(36) NULL,
    action_type     ENUM('invoice_extraction','voice_transcribe','voice_intent','report_generation','chatbot') NOT NULL,
    model_name      VARCHAR(50) NOT NULL,
    prompt_tokens   INT DEFAULT 0,
    completion_tokens INT DEFAULT 0,
    total_tokens    INT DEFAULT 0,
    estimated_cost  DECIMAL(10,6) DEFAULT 0,
    request_metadata JSON NULL,
    created_at      DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_tenant_date (tenant_id, created_at),
    FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 6. Notifications Table
CREATE TABLE IF NOT EXISTS notifications (
    id              CHAR(36) PRIMARY KEY DEFAULT (UUID()),
    tenant_id       CHAR(36) NOT NULL,
    user_id         CHAR(36) NULL,
    type            ENUM('invoice_processed','invoice_rejected','quota_warning','month_end','system','achievement') NOT NULL,
    title           VARCHAR(255) NOT NULL,
    body            TEXT NOT NULL,
    is_read         BOOLEAN DEFAULT FALSE,
    metadata        JSON NULL,
    created_at      DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_user_read (user_id, is_read),
    FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
