-- ─── Invoices ─────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS invoices (
    id                   CHAR(36) NOT NULL DEFAULT (UUID()),
    tenant_id            CHAR(36) NOT NULL,
    company_id           CHAR(36) NOT NULL,
    uploaded_by          CHAR(36) NULL,
    invoice_number       VARCHAR(100) NULL,
    invoice_date         DATE NULL,
    invoice_type         ENUM('cash','credit') NOT NULL DEFAULT 'cash',
    ubl_type_code        CHAR(3) NOT NULL DEFAULT '388',
    payment_method_code  CHAR(3) NOT NULL DEFAULT '013',
    supplier_tin         VARCHAR(20) NULL,
    supplier_name        VARCHAR(255) NULL,
    supplier_address     TEXT NULL,
    buyer_tin            VARCHAR(20) NULL,
    buyer_national_id    VARCHAR(20) NULL,
    buyer_name           VARCHAR(255) NULL,
    subtotal             DECIMAL(15,3) NOT NULL DEFAULT 0,
    discount_total       DECIMAL(15,3) NOT NULL DEFAULT 0,
    tax_amount           DECIMAL(15,3) NOT NULL DEFAULT 0,
    grand_total          DECIMAL(15,3) NOT NULL DEFAULT 0,
    currency_code        CHAR(3) NOT NULL DEFAULT 'JOD',
    status               ENUM('uploaded','extracting','extracted','validated',
                         'validation_failed','submitting','approved','rejected')
                         NOT NULL DEFAULT 'uploaded',
    original_file_path   TEXT NULL,
    original_file_hash   VARCHAR(64) NULL,
    invoice_category     VARCHAR(20) NOT NULL DEFAULT 'simplified',
    validation_errors    JSON NULL,
    qr_code              TEXT NULL,
    jofotara_response    JSON NULL,
    ai_provider          VARCHAR(20) NULL,
    ai_confidence_score  DECIMAL(4,3) NULL,
    ai_prompt_tokens     INT NOT NULL DEFAULT 0,
    ai_completion_tokens INT NOT NULL DEFAULT 0,
    ai_total_cost        DECIMAL(10,6) NOT NULL DEFAULT 0,
    ai_raw_response      JSON NULL,
    idempotency_key      VARCHAR(64) NULL,
    created_at           DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at           DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    deleted_at           DATETIME NULL,
    PRIMARY KEY (id),
    UNIQUE KEY uq_idempotency (idempotency_key),
    INDEX idx_invoices_tenant (tenant_id),
    INDEX idx_invoices_company (company_id),
    INDEX idx_invoices_status (status),
    INDEX idx_invoices_date (invoice_date),
    INDEX idx_invoices_file_hash (original_file_hash),
    CONSTRAINT fk_inv_tenant  FOREIGN KEY (tenant_id)   REFERENCES tenants(id)   ON DELETE CASCADE,
    CONSTRAINT fk_inv_company FOREIGN KEY (company_id)  REFERENCES companies(id) ON DELETE CASCADE,
    CONSTRAINT fk_inv_user    FOREIGN KEY (uploaded_by) REFERENCES users(id)     ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ─── Invoice Lines ────────────────────────────────────────
CREATE TABLE IF NOT EXISTS invoice_lines (
    id          CHAR(36) NOT NULL DEFAULT (UUID()),
    invoice_id  CHAR(36) NOT NULL,
    line_number INT NOT NULL,
    description TEXT NOT NULL,
    quantity    DECIMAL(15,3) NOT NULL,
    unit_price  DECIMAL(15,3) NOT NULL,
    discount    DECIMAL(15,3) NOT NULL DEFAULT 0,
    tax_rate    DECIMAL(5,4) NOT NULL,
    tax_amount  DECIMAL(15,3) NOT NULL DEFAULT 0,
    line_total  DECIMAL(15,3) NOT NULL,
    PRIMARY KEY (id),
    INDEX idx_lines_invoice (invoice_id),
    CONSTRAINT fk_lines_invoice FOREIGN KEY (invoice_id) REFERENCES invoices(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
