-- NIS2 Migration 013: Firm-Organization assignments + KB tracking
-- Database: nis2_agile_db
-- Data: 2026-04-11

USE nis2_agile_db;

-- 1. Mapping firm -> organization (M:N)
CREATE TABLE IF NOT EXISTS firm_org_assignments (
    id                  INT AUTO_INCREMENT PRIMARY KEY,
    consulting_firm_id  INT NOT NULL,
    organization_id     INT NOT NULL,
    assigned_to         INT NOT NULL DEFAULT 0
                         COMMENT '0=tutti i membri del firm, user_id=membro specifico',
    assigned_by         INT NOT NULL,
    created_at          DATETIME DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY uk_firm_org_user (consulting_firm_id, organization_id, assigned_to),
    INDEX idx_firm (consulting_firm_id),
    INDEX idx_org (organization_id),
    INDEX idx_assigned (assigned_to)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 2. Registro documenti uploadati nella KB (audit + listing)
CREATE TABLE IF NOT EXISTS kb_uploaded_documents (
    id                  INT AUTO_INCREMENT PRIMARY KEY,
    qdrant_doc_uuid     VARCHAR(64) NOT NULL COMMENT 'Identifica il gruppo di chunk in Qdrant (per delete-by-filter)',
    scope               ENUM('SYSTEM','FIRM','ORG') NOT NULL DEFAULT 'SYSTEM',
    consulting_firm_id  INT NULL,
    organization_id     INT NULL,
    uploaded_by         INT NOT NULL,
    title               VARCHAR(255) NOT NULL,
    entity_type         VARCHAR(64)  NULL,
    source              VARCHAR(255) NULL,
    lang                VARCHAR(5)   NOT NULL DEFAULT 'it',
    chunk_count         INT NOT NULL DEFAULT 0,
    shared_with_orgs    JSON NULL COMMENT 'Array di organization_id quando scope=FIRM',
    status              ENUM('processing','ready','failed') NOT NULL DEFAULT 'ready',
    created_at          DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_scope_firm (scope, consulting_firm_id),
    INDEX idx_scope_org (scope, organization_id),
    INDEX idx_uuid (qdrant_doc_uuid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
