-- 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,
    profile_id BIGINT NOT NULL REFERENCES profiles(id) DEFAULT 1
);

-- 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 profile+table combination
CREATE UNIQUE INDEX idx_table_definitions_profile_table
    ON table_definitions (profile_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);
