-- Migration: 002_sequence_by_name
-- Adds a sequence table that uses schema name instead of UUID for simpler operation

BEGIN;

-- Create a simpler sequences table using schema name
CREATE TABLE IF NOT EXISTS sequences_by_name (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    schema_name TEXT NOT NULL,
    scope TEXT NOT NULL,
    current_value INTEGER NOT NULL DEFAULT 0,
    UNIQUE(schema_name, scope)
);

CREATE INDEX IF NOT EXISTS idx_sequences_by_name ON sequences_by_name(schema_name, scope);

-- Function to get next sequence by schema name
CREATE OR REPLACE FUNCTION next_sequence_by_name(
    p_schema_name TEXT,
    p_scope TEXT
) RETURNS INTEGER AS $$
DECLARE
    v_next INTEGER;
BEGIN
    INSERT INTO sequences_by_name (schema_name, scope, current_value)
    VALUES (p_schema_name, p_scope, 1)
    ON CONFLICT (schema_name, scope) DO UPDATE
    SET current_value = sequences_by_name.current_value + 1
    RETURNING current_value INTO v_next;

    RETURN v_next;
END;
$$ LANGUAGE plpgsql;

COMMIT;
