-- Main table definitions

CREATE TABLE table_definitions (
    id BIGSERIAL PRIMARY KEY,
    deleted BOOLEAN NOT NULL DEFAULT FALSE,
    table_name TEXT NOT NULL,
    columns JSONB NOT NULL,
    indexes JSONB NOT NULL,
    created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
    schema_id BIGINT NOT NULL REFERENCES schemas(id)
);

-- Relationship table for multiple links
CREATE TABLE table_definition_links (
    source_table_id BIGINT NOT NULL REFERENCES table_definitions(id) ON DELETE CASCADE,
    linked_table_id BIGINT NOT NULL REFERENCES table_definitions(id),
    is_required BOOLEAN NOT NULL DEFAULT FALSE,
    created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (source_table_id, linked_table_id)
);

-- Create composite unique index for schema+table combination
CREATE UNIQUE INDEX idx_table_definitions_schema_table
    ON table_definitions (schema_id, table_name);

CREATE INDEX idx_links_source ON table_definition_links (source_table_id);
CREATE INDEX idx_links_target ON table_definition_links (linked_table_id);

