#!/usr/bin/env bash
# Skriv en melding til en chat som Claude Code.
# Bruker PG direkte med access-propagering.
#
# Bruk: ./scripts/chat-reply.sh <chat-id> "<melding>"

set -euo pipefail

CHAT_ID="${1:?Mangler chat-id}"
MESSAGE="${2:?Mangler melding}"
CLAUDE_ID="d3eebc99-9c0b-4ef8-bb6d-6bb9bd380a44"

# Skriv melding + edge + propager access til alle chat-deltakere
docker exec sidelinja-postgres-1 psql -U sidelinja -d synops -q -c "
DO \$\$
DECLARE
    new_id UUID := gen_random_uuid();
    new_edge UUID := gen_random_uuid();
    member_rec RECORD;
BEGIN
    -- Opprett meldings-node
    INSERT INTO nodes (id, node_kind, content, visibility, created_by)
    VALUES (new_id, 'content', '$MESSAGE', 'hidden', '$CLAUDE_ID');

    -- belongs_to-edge til chatten
    INSERT INTO edges (id, source_id, target_id, edge_type)
    VALUES (new_edge, new_id, '$CHAT_ID', 'belongs_to');

    -- Propager access til alle deltakere i chatten
    FOR member_rec IN
        SELECT e.source_id FROM edges e
        WHERE e.target_id = '$CHAT_ID'
        AND e.edge_type IN ('owner', 'member_of')
    LOOP
        INSERT INTO node_access (subject_id, object_id, access, via_edge)
        VALUES (member_rec.source_id, new_id, 'reader', new_edge)
        ON CONFLICT DO NOTHING;
    END LOOP;
END \$\$;
"

echo "Svar sendt til chat $CHAT_ID"
