package com.agent.management.rag.capability;

import java.util.List;

public record SqlSchemaSnapshot(List<TableSchema> tables, List<ForeignKey> foreignKeys) {
    public SqlSchemaSnapshot(List<TableSchema> tables) { this(tables, List.of()); }
    public SqlSchemaSnapshot { tables = List.copyOf(tables == null ? List.of() : tables); foreignKeys=List.copyOf(foreignKeys==null?List.of():foreignKeys); }
    public record TableSchema(String name, String description, List<ColumnSchema> columns) {
        public TableSchema { columns = List.copyOf(columns == null ? List.of() : columns); }
    }
    public record ColumnSchema(String name, String type, String description) {}
    public record ForeignKey(String name,String sourceTable,String sourceColumn,String targetTable,String targetColumn) {}

    public String toDdl(List<String> selectedTables) {
        var allowed = selectedTables == null || selectedTables.isEmpty() ? null : new java.util.HashSet<>(selectedTables);
        StringBuilder ddl = new StringBuilder();
        for (TableSchema table : tables) {
            if (allowed != null && !allowed.contains(table.name())) continue;
            ddl.append("TABLE ").append(table.name()).append(" (");
            ddl.append(table.columns().stream().map(column -> column.name() + " " + column.type()
                    + (column.description() == null || column.description().isBlank() ? "" : " /* " + column.description() + " */"))
                    .collect(java.util.stream.Collectors.joining(", ")));
            ddl.append(");\n");
        }
        for (ForeignKey key : foreignKeys) if ((allowed==null||allowed.contains(key.sourceTable())) && (allowed==null||allowed.contains(key.targetTable())))
            ddl.append("FOREIGN KEY ").append(key.sourceTable()).append('.').append(key.sourceColumn()).append(" -> ").append(key.targetTable()).append('.').append(key.targetColumn()).append(";\n");
        return ddl.toString();
    }
}
