-- Migration 120: Telefoni (Yealink) module
-- Dato: 12. februar 2026

-- Add telephony fields to users (chosen approach)
ALTER TABLE users
    ADD COLUMN IF NOT EXISTS telefoni_extension VARCHAR(16),
    ADD COLUMN IF NOT EXISTS telefoni_aktiv BOOLEAN NOT NULL DEFAULT FALSE;

CREATE INDEX IF NOT EXISTS idx_users_telefoni_extension ON users(telefoni_extension);
CREATE INDEX IF NOT EXISTS idx_users_telefoni_aktiv ON users(telefoni_aktiv);

-- Call log table (isolated)
CREATE TABLE IF NOT EXISTS telefoni_opkald (
    id BIGSERIAL PRIMARY KEY,
    callid VARCHAR(128) NOT NULL,
    bruger_id INTEGER,
    direction VARCHAR(16) NOT NULL CHECK (direction IN ('inbound', 'outbound')),
    ekstern_nummer VARCHAR(32),
    intern_extension VARCHAR(16),
    kontakt_id INTEGER,
    sag_id INTEGER,
    started_at TIMESTAMP NOT NULL,
    ended_at TIMESTAMP,
    duration_sec INTEGER,
    raw_payload JSONB NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- Ensure idempotency per call
CREATE UNIQUE INDEX IF NOT EXISTS ux_telefoni_opkald_callid ON telefoni_opkald(callid);
CREATE INDEX IF NOT EXISTS idx_telefoni_opkald_bruger_id ON telefoni_opkald(bruger_id);
CREATE INDEX IF NOT EXISTS idx_telefoni_opkald_ekstern_nummer ON telefoni_opkald(ekstern_nummer);
CREATE INDEX IF NOT EXISTS idx_telefoni_opkald_started_at ON telefoni_opkald(started_at);
CREATE INDEX IF NOT EXISTS idx_telefoni_opkald_sag_id ON telefoni_opkald(sag_id);
