-- AnyDesk Remote Session Management
-- Tracks remote support sessions started via AnyDesk integration
-- Sessions can be linked to contacts, companies, or cases for activity history and time tracking

CREATE TABLE IF NOT EXISTS anydesk_sessions (
    id SERIAL PRIMARY KEY,
    anydesk_session_id VARCHAR(255) UNIQUE NOT NULL,  -- External AnyDesk session ID
    
    -- Relationship fields (at least one should be set)
    contact_id INTEGER REFERENCES contacts(id) ON DELETE SET NULL,
    customer_id INTEGER REFERENCES customers(id) ON DELETE SET NULL,
    sag_id INTEGER REFERENCES sag_sager(id) ON DELETE SET NULL,
    
    -- Session details
    session_link TEXT,  -- Generated AnyDesk link (unique access code)
    device_info JSONB DEFAULT '{}',  -- Device info: os, device_type, etc.
    created_by_user_id INTEGER REFERENCES users(user_id) ON DELETE SET NULL,
    
    -- Session lifecycle
    started_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
    ended_at TIMESTAMP WITH TIME ZONE,
    duration_minutes INTEGER,  -- Calculated from started_at to ended_at
    
    -- Session status: draft, pending, active, completed, failed, cancelled
    status VARCHAR(50) NOT NULL DEFAULT 'draft',
    error_message TEXT,
    
    -- Timestamps
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    
    -- Audit trail
    metadata JSONB DEFAULT '{}'  -- Flexible storage for additional info
);

-- Create indexes for common queries
CREATE INDEX IF NOT EXISTS idx_anydesk_sessions_contact_id ON anydesk_sessions(contact_id);
CREATE INDEX IF NOT EXISTS idx_anydesk_sessions_customer_id ON anydesk_sessions(customer_id);
CREATE INDEX IF NOT EXISTS idx_anydesk_sessions_sag_id ON anydesk_sessions(sag_id);
CREATE INDEX IF NOT EXISTS idx_anydesk_sessions_created_by_user_id ON anydesk_sessions(created_by_user_id);
CREATE INDEX IF NOT EXISTS idx_anydesk_sessions_status ON anydesk_sessions(status);
CREATE INDEX IF NOT EXISTS idx_anydesk_sessions_started_at ON anydesk_sessions(started_at DESC);

-- View: Session history with related data (for timeline/activity log)
CREATE OR REPLACE VIEW anydesk_session_timeline AS
SELECT 
    s.id,
    s.anydesk_session_id,
    s.contact_id,
    c.first_name || ' ' || c.last_name as contact_name,
    s.customer_id,
    cust.name as customer_name,
    s.sag_id,
    sag.title as sag_title,
    s.session_link,
    s.started_at,
    s.ended_at,
    s.duration_minutes,
    s.status,
    u.full_name as started_by_user,
    s.created_at
FROM anydesk_sessions s
LEFT JOIN contacts c ON s.contact_id = c.id
LEFT JOIN customers cust ON s.customer_id = cust.id
LEFT JOIN sag_sager sag ON s.sag_id = sag.id
LEFT JOIN users u ON s.created_by_user_id = u.user_id
ORDER BY s.started_at DESC;
