-- Blueprints table for structured project specifications
CREATE TABLE IF NOT EXISTS blueprints (
    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    project_id  TEXT NOT NULL,
    name        TEXT NOT NULL,
    description TEXT,
    spec        JSONB NOT NULL DEFAULT '{}',  -- Structured specification
    created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at  TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Index for project lookups
CREATE INDEX IF NOT EXISTS idx_blueprints_project
    ON blueprints(project_id, created_at DESC);

-- GIN index for efficient JSONB queries
CREATE INDEX IF NOT EXISTS idx_blueprints_spec_gin
    ON blueprints USING GIN (spec);

-- Update trigger for blueprints.updated_at
CREATE OR REPLACE FUNCTION update_blueprints_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER blueprints_updated_at
    BEFORE UPDATE ON blueprints
    FOR EACH ROW
    EXECUTE FUNCTION update_blueprints_updated_at();

COMMENT ON TABLE blueprints IS 'Project blueprints with structured specifications';
COMMENT ON COLUMN blueprints.spec IS 'JSONB specification with project requirements, architecture, components, etc.';
