-- Phase 4: Voice/Video Calls Migration
-- WebRTC integration with TURN server support
-- Migration: 20260110140000

-- Extend calls table for voice/video call support
ALTER TABLE calls 
ADD COLUMN IF NOT EXISTS type VARCHAR(20) DEFAULT 'voice', -- voice, video
ADD COLUMN IF NOT EXISTS sfu_room_id VARCHAR(100), -- For group calls (Mediasoup)
ADD COLUMN IF NOT EXISTS recording_url VARCHAR(500),
ADD COLUMN IF NOT EXISTS quality_stats JSONB;

-- Extend call_participants table for WebRTC stats
ALTER TABLE call_participants
ADD COLUMN IF NOT EXISTS ice_candidates JSONB,
ADD COLUMN IF NOT EXISTS media_state JSONB DEFAULT '{"audio": true, "video": false, "screenShare": false}',
ADD COLUMN IF NOT EXISTS media_stats JSONB,
ADD COLUMN IF NOT EXISTS connection_quality VARCHAR(20) DEFAULT 'good'; -- excellent, good, poor, failed

-- Create turn_credentials table for temporary TURN server credentials
CREATE TABLE IF NOT EXISTS turn_credentials (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id VARCHAR NOT NULL ,
  username VARCHAR(100) NOT NULL,
  credential VARCHAR(100) NOT NULL,
  created_at TIMESTAMP DEFAULT NOW(),
  expires_at TIMESTAMP DEFAULT NOW() + INTERVAL '24 hours',
  UNIQUE(user_id)
);

-- Indexes for performance
CREATE INDEX IF NOT EXISTS idx_calls_type ON calls(type);
CREATE INDEX IF NOT EXISTS idx_calls_sfu_room ON calls(sfu_room_id) WHERE sfu_room_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_turn_user_expires ON turn_credentials(user_id, expires_at);
CREATE INDEX IF NOT EXISTS idx_call_participants_quality ON call_participants(connection_quality);

-- Function to cleanup expired TURN credentials
CREATE OR REPLACE FUNCTION cleanup_expired_turn_credentials()
RETURNS INTEGER AS $$
DECLARE
  deleted_count INTEGER;
BEGIN
  DELETE FROM turn_credentials
  WHERE expires_at < NOW();
  
  GET DIAGNOSTICS deleted_count = ROW_COUNT;
  RETURN deleted_count;
END;
$$ LANGUAGE plpgsql;

-- Comments
COMMENT ON COLUMN calls.type IS 'Type of call: voice or video';
COMMENT ON COLUMN calls.sfu_room_id IS 'Mediasoup SFU room ID for group calls';
COMMENT ON COLUMN calls.recording_url IS 'URL to call recording if enabled';
COMMENT ON COLUMN calls.quality_stats IS 'Aggregated quality statistics for the call';
COMMENT ON COLUMN call_participants.ice_candidates IS 'ICE candidates exchanged during call setup';
COMMENT ON COLUMN call_participants.media_state IS 'Current media state (audio, video, screenShare)';
COMMENT ON COLUMN call_participants.media_stats IS 'WebRTC statistics for this participant';
COMMENT ON COLUMN call_participants.connection_quality IS 'Real-time connection quality indicator';
COMMENT ON TABLE turn_credentials IS 'Temporary TURN server credentials for NAT traversal';
