import { getSupabaseConfig, saveSupabaseConfig, getSupabaseSyncResult, saveSupabaseSyncResult, } from '../storage/supabase-store.js';
import { fetchTables, fetchRlsPolicies } from '../engine/supabase/schema-fetcher.js';
import { generateRlsSpecTitle, generateRlsSpecDescription, generateRlsAcceptanceCriteria, classifyRlsRisk, } from '../engine/supabase/rls-spec-generator.js';
import { handleCreateSpec } from './create-spec.js';
export async function handleConfigureSupabase(input) {
    const { projectPath, projectUrl, serviceRoleKey, anonKey } = input;
    if (!projectUrl.startsWith('https://') || !projectUrl.includes('.supabase.co')) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'Invalid Supabase project URL. Expected format: https://xxx.supabase.co',
                },
            ],
            isError: true,
        };
    }
    const config = {
        projectUrl,
        serviceRoleKey,
        anonKey,
        configuredAt: new Date().toISOString(),
    };
    await saveSupabaseConfig(projectPath, config);
    return {
        content: [
            {
                type: 'text',
                text: [
                    'Supabase configured successfully.',
                    `Project URL: ${projectUrl}`,
                    'Run sync_supabase_schema to fetch your database schema.',
                ].join('\n'),
            },
        ],
    };
}
export async function handleSupabaseStatus(input) {
    const { projectPath } = input;
    const config = await getSupabaseConfig(projectPath);
    if (!config) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'Supabase no está conectado. Usa start_oauth_flow con integration="supabase" para ver las instrucciones.',
                },
            ],
        };
    }
    const syncResult = await getSupabaseSyncResult(projectPath);
    const lines = [
        `Project URL: ${config.projectUrl}`,
        `Configured at: ${config.configuredAt}`,
        `Anon key: ${config.anonKey ? 'set' : 'not set'}`,
    ];
    if (syncResult) {
        lines.push('');
        lines.push(`Last sync: ${syncResult.syncedAt}`);
        lines.push(`Tables synced: ${syncResult.tables.length}`);
        const tablesWithRls = syncResult.tables.filter((t) => t.hasRls).length;
        lines.push(`Tables with RLS: ${tablesWithRls} / ${syncResult.tables.length}`);
    }
    else {
        lines.push('');
        lines.push('No schema sync performed yet. Run sync_supabase_schema.');
    }
    return { content: [{ type: 'text', text: lines.join('\n') }] };
}
export async function handleSyncSupabaseSchema(input) {
    const { projectPath, schemas = ['public'] } = input;
    const config = await getSupabaseConfig(projectPath);
    if (!config) {
        return {
            content: [
                {
                    type: 'text',
                    text: 'Supabase no está conectado. Usa start_oauth_flow con integration="supabase" para ver las instrucciones.',
                },
            ],
            isError: true,
        };
    }
    const tables = await fetchTables(config, schemas);
    const policies = await fetchRlsPolicies(config);
    // Attach policies to tables
    for (const table of tables) {
        table.rlsPolicies = policies.filter((p) => p.table === table.name);
        table.hasRls = table.rlsPolicies.length > 0;
    }
    const syncResult = {
        tables,
        syncedAt: new Date().toISOString(),
        projectUrl: config.projectUrl,
    };
    await saveSupabaseSyncResult(projectPath, syncResult);
    const withRls = tables.filter((t) => t.hasRls).length;
    const withoutRls = tables.filter((t) => !t.hasRls).length;
    return {
        content: [
            {
                type: 'text',
                text: [
                    `Schema synced successfully.`,
                    `Tables found: ${tables.length}`,
                    `  With RLS: ${withRls}`,
                    `  Without RLS: ${withoutRls}`,
                    `Schemas: ${schemas.join(', ')}`,
                    `Synced at: ${syncResult.syncedAt}`,
                    '',
                    withoutRls > 0
                        ? `Warning: ${withoutRls} table(s) have no RLS policies. Run generate_rls_spec to create security specs.`
                        : 'All tables have RLS policies.',
                ].join('\n'),
            },
        ],
    };
}
export async function handleGenerateRlsSpec(input) {
    const { projectPath, tableName, createMissingRlsSpecs = true } = input;
    const syncResult = await getSupabaseSyncResult(projectPath);
    if (!syncResult) {
        return {
            content: [{ type: 'text', text: 'No schema sync found. Run sync_supabase_schema first.' }],
            isError: true,
        };
    }
    const targetTables = tableName
        ? syncResult.tables.filter((t) => t.name === tableName)
        : syncResult.tables;
    if (targetTables.length === 0) {
        return {
            content: [
                {
                    type: 'text',
                    text: `No table found${tableName ? ` named "${tableName}"` : ''}. Run sync_supabase_schema first.`,
                },
            ],
            isError: true,
        };
    }
    const specIds = [];
    const tablesWithoutRls = [];
    const errors = [];
    for (const table of targetTables) {
        const shouldCreate = createMissingRlsSpecs || table.hasRls;
        if (!table.hasRls) {
            tablesWithoutRls.push(table.name);
        }
        if (!shouldCreate) {
            continue;
        }
        const risk = classifyRlsRisk(table);
        const title = generateRlsSpecTitle(table);
        const description = generateRlsSpecDescription(table);
        const criteria = generateRlsAcceptanceCriteria(table);
        const createInput = {
            title,
            description: [
                description,
                '',
                '## Acceptance Criteria',
                ...criteria.map((c) => `- [ ] ${c}`),
            ].join('\n'),
            projectPath,
            type: 'infra',
            target: 'database',
            tags: ['security', 'rls', 'supabase', risk],
        };
        try {
            const result = await handleCreateSpec(createInput);
            if (!result.isError) {
                // Extract spec ID from result text (format: SPEC-XXX)
                const match = /SPEC-(\d+)/.exec(result.content[0]?.text ?? '');
                if (match) {
                    specIds.push(`SPEC-${match[1]}`);
                }
            }
            else {
                errors.push(`Failed to create spec for ${table.name}`);
            }
        }
        catch (err) {
            errors.push(`Error creating spec for ${table.name}: ${err instanceof Error ? err.message : String(err)}`);
        }
    }
    const summary = {
        specsCreated: specIds.length,
        specIds,
        tablesWithoutRls,
    };
    const lines = [
        `RLS specs generated: ${specIds.length}`,
        specIds.length > 0 ? `Spec IDs: ${specIds.join(', ')}` : '',
        tablesWithoutRls.length > 0 ? `Tables without RLS: ${tablesWithoutRls.join(', ')}` : '',
        errors.length > 0 ? `Errors: ${errors.join('; ')}` : '',
    ].filter(Boolean);
    return {
        content: [{ type: 'text', text: lines.join('\n') }],
        structuredContent: summary,
    };
}
//# sourceMappingURL=supabase-handler.js.map