// SPEC-597-EXEMPT: canonical mapping (npm-package↔framework, keyword catalogue)
// — must enumerate framework names by design; no detection logic to migrate.
// Planu — DB Engine Detection (SPEC-025)
// Detects database engine from project dependencies and generates adapted SQL syntax
import { readFile } from 'node:fs/promises';
import { collectDependencies } from '../detection-utils.js';
// === Registry loading ===
let registryCache = null;
/** Resets the in-memory cache — used in tests to force reload */
export function resetDbRegistryCache() {
    registryCache = null;
}
async function loadDbRegistry() {
    if (registryCache) {
        return registryCache;
    }
    try {
        const configPath = new URL('../../config/db-engines.json', import.meta.url);
        const content = await readFile(configPath, 'utf-8');
        registryCache = JSON.parse(content);
        return registryCache;
    }
    catch {
        return {
            engines: {},
            sqlSyntax: { createTable: {}, primaryKeyConstraint: {}, autoTimestamps: {} },
        };
    }
}
// === DB Engine detection ===
export async function detectDBEngine(projectPath) {
    const registry = await loadDbRegistry();
    const deps = await collectDependencies(projectPath);
    for (const [engineKey, engine] of Object.entries(registry.engines)) {
        const allDeps = [...engine.detectionDeps, ...(engine.prismaDeps ?? [])];
        for (const dep of allDeps) {
            if (deps.has(dep)) {
                return {
                    engine: engineKey,
                    detectedFrom: dep,
                    features: engine.features,
                    securityRules: engine.securityRules,
                };
            }
        }
    }
    return null;
}
// === SQL syntax adapters ===
export function getSQLSyntaxForEngine(engine) {
    const defaults = {
        createTable: 'CREATE TABLE IF NOT EXISTS',
        primaryKey: 'PRIMARY KEY',
        autoTimestamp: 'DEFAULT now()',
        idType: 'uuid DEFAULT gen_random_uuid()',
        jsonType: 'jsonb',
        autoIncrement: 'GENERATED ALWAYS AS IDENTITY',
    };
    switch (engine) {
        case 'supabase':
        case 'postgresql':
            return {
                createTable: 'CREATE TABLE IF NOT EXISTS',
                primaryKey: 'PRIMARY KEY',
                autoTimestamp: 'DEFAULT now()',
                idType: 'uuid DEFAULT gen_random_uuid()',
                jsonType: 'jsonb',
                autoIncrement: 'GENERATED ALWAYS AS IDENTITY',
            };
        case 'mysql':
            return {
                createTable: 'CREATE TABLE IF NOT EXISTS',
                primaryKey: 'PRIMARY KEY',
                autoTimestamp: 'DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
                idType: 'CHAR(36) DEFAULT (UUID())',
                jsonType: 'JSON',
                autoIncrement: 'AUTO_INCREMENT',
            };
        case 'sqlite':
            return {
                createTable: 'CREATE TABLE IF NOT EXISTS',
                primaryKey: 'PRIMARY KEY',
                autoTimestamp: "DEFAULT (datetime('now'))",
                idType: 'TEXT DEFAULT (lower(hex(randomblob(16))))',
                jsonType: 'TEXT',
                autoIncrement: 'AUTOINCREMENT',
            };
        case 'mongodb':
            return {
                createTable: 'db.createCollection',
                primaryKey: '_id',
                autoTimestamp: 'ISODate()',
                idType: 'ObjectId',
                jsonType: 'BSON',
                autoIncrement: 'ObjectId()',
            };
        case 'firebase':
            return {
                createTable: '// Firestore collection (no DDL)',
                primaryKey: 'document.id',
                autoTimestamp: 'FieldValue.serverTimestamp()',
                idType: 'string (auto-generated)',
                jsonType: 'Map<string, any>',
                autoIncrement: 'Firestore auto-ID',
            };
        default:
            return defaults;
    }
}
// === Firestore security rules generation ===
export function generateFirestoreRules(collections) {
    const rules = [
        "rules_version = '2';",
        'service cloud.firestore {',
        '  match /databases/{database}/documents {',
    ];
    for (const collection of collections) {
        rules.push(`    match /${collection}/{document=**} {`, `      allow read: if request.auth != null;`, `      allow write: if request.auth != null && request.auth.uid == resource.data.userId;`, `    }`);
    }
    rules.push('  }', '}');
    return rules.join('\n');
}
// === MongoDB schema generation ===
export function generateMongoSchema(collections) {
    const lines = ['// MongoDB Collection Schemas', ''];
    for (const collection of collections) {
        lines.push(`// ${collection} collection`, `db.createCollection("${collection}", {`, `  validator: {`, `    $jsonSchema: {`, `      bsonType: "object",`, `      required: ["_id", "createdAt", "updatedAt"],`, `      properties: {`, `        _id: { bsonType: "objectId", description: "Primary key" },`, `        createdAt: { bsonType: "date", description: "Creation timestamp" },`, `        updatedAt: { bsonType: "date", description: "Last update timestamp" }`, `      }`, `    }`, `  }`, `});`, ``, `db.${collection}.createIndex({ createdAt: -1 });`, ``);
    }
    return lines.join('\n');
}
// === Supabase RLS helper ===
export function generateSupabaseRLS(tables) {
    const lines = ['-- Supabase RLS Policies', ''];
    for (const table of tables) {
        lines.push(`-- Enable RLS on ${table}`, `ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY;`, ``, `-- Allow authenticated users to read`, `CREATE POLICY "${table}_select_authenticated"`, `  ON ${table} FOR SELECT`, `  USING (auth.role() = 'authenticated');`, ``, `-- Allow users to manage their own records`, `CREATE POLICY "${table}_all_owner"`, `  ON ${table} FOR ALL`, `  USING (auth.uid() = user_id)`, `  WITH CHECK (auth.uid() = user_id);`, ``);
    }
    return lines.join('\n');
}
//# sourceMappingURL=db-engine.js.map