-- ════════════════════════════════════════════════════════════
-- مُصادَق — Complete Phase 1 Migration (MySQL 8.0 Compatible)
-- ════════════════════════════════════════════════════════════

-- 1. Invoice Line Items (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,
    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. AI Usage Log
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;

-- 4. Notifications
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;

-- ════════════════════════════════════════════════════════════
-- 5. Safe ALTER TABLE (MySQL 8 compatible — no IF NOT EXISTS)
--    Run each block separately. If column already exists, 
--    MySQL will show "Duplicate column" error — just skip it.
-- ════════════════════════════════════════════════════════════

-- 5a. Companies: JoFotara credentials
-- Run these ONE BY ONE. Skip any that say "Duplicate column name"

ALTER TABLE companies ADD COLUMN jofotara_client_id VARCHAR(255) NULL;
ALTER TABLE companies ADD COLUMN jofotara_secret_key VARCHAR(255) NULL;
ALTER TABLE companies ADD COLUMN jofotara_status ENUM('active', 'inactive', 'pending') DEFAULT 'inactive';

-- 5b. Invoices: AI + JoFotara metadata
-- Run these ONE BY ONE. Skip any that say "Duplicate column name"

ALTER TABLE invoices ADD COLUMN invoice_category ENUM('simplified', 'standard') DEFAULT 'simplified';
ALTER TABLE invoices ADD COLUMN ubl_type_code VARCHAR(10) DEFAULT '388';
ALTER TABLE invoices ADD COLUMN payment_method_code VARCHAR(10) DEFAULT '013';
ALTER TABLE invoices ADD COLUMN validation_warnings JSON NULL;
ALTER TABLE invoices ADD COLUMN ai_confidence DECIMAL(5,2) DEFAULT 0;
ALTER TABLE invoices ADD COLUMN jofotara_uuid VARCHAR(100) NULL;
