-- Migration 165: AnyDesk IDs per case (multi-ID support)
-- Stores quick-connect IDs on cases and optional hardware relation

CREATE TABLE IF NOT EXISTS sag_anydesk_ids (
    id SERIAL PRIMARY KEY,
    sag_id INTEGER NOT NULL REFERENCES sag_sager(id) ON DELETE CASCADE,
    anydesk_id VARCHAR(64) NOT NULL,
    hardware_asset_id INTEGER REFERENCES hardware_assets(id) ON DELETE SET NULL,
    is_primary BOOLEAN NOT NULL DEFAULT FALSE,
    note TEXT,
    created_by_user_id INTEGER REFERENCES users(user_id) ON DELETE SET NULL,
    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP WITH TIME ZONE,
    UNIQUE (sag_id, anydesk_id)
);

CREATE INDEX IF NOT EXISTS idx_sag_anydesk_ids_sag_id
    ON sag_anydesk_ids(sag_id)
    WHERE deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_sag_anydesk_ids_anydesk_id
    ON sag_anydesk_ids(anydesk_id)
    WHERE deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_sag_anydesk_ids_hardware_asset_id
    ON sag_anydesk_ids(hardware_asset_id)
    WHERE deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_sag_anydesk_ids_primary
    ON sag_anydesk_ids(sag_id, is_primary)
    WHERE deleted_at IS NULL;

-- Keep updated_at fresh
CREATE OR REPLACE FUNCTION update_sag_anydesk_ids_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS trg_update_sag_anydesk_ids_updated_at ON sag_anydesk_ids;
CREATE TRIGGER trg_update_sag_anydesk_ids_updated_at
    BEFORE UPDATE ON sag_anydesk_ids
    FOR EACH ROW
    EXECUTE FUNCTION update_sag_anydesk_ids_updated_at();
