-- Ticket Contacts - Many-to-many relation med roller
-- Tillader flere kontakter per ticket med forskellige roller (primary, cc, observer, etc.)

-- Junction tabel mellem tickets og contacts
CREATE TABLE IF NOT EXISTS tticket_contacts (
    id SERIAL PRIMARY KEY,
    ticket_id INTEGER NOT NULL REFERENCES tticket_tickets(id) ON DELETE CASCADE,
    contact_id INTEGER NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
    role VARCHAR(50) NOT NULL DEFAULT 'observer',  -- primary, cc, observer, assignee
    added_by_user_id INTEGER REFERENCES users(user_id),
    added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    notes TEXT,  -- Valgfri noter om kontaktens rolle
    
    -- Forhindre dubletter
    UNIQUE(ticket_id, contact_id)
);

-- Indices for performance
CREATE INDEX IF NOT EXISTS idx_tticket_contacts_ticket ON tticket_contacts(ticket_id);
CREATE INDEX IF NOT EXISTS idx_tticket_contacts_contact ON tticket_contacts(contact_id);
CREATE INDEX IF NOT EXISTS idx_tticket_contacts_role ON tticket_contacts(role);

-- Check constraint for valide roller
ALTER TABLE tticket_contacts 
ADD CONSTRAINT tticket_contacts_role_check 
CHECK (role IN ('primary', 'cc', 'observer', 'assignee', 'requester'));

-- Migrer eksisterende contact_id til ny tabel (hvis der er data)
INSERT INTO tticket_contacts (ticket_id, contact_id, role)
SELECT id, contact_id, 'primary'
FROM tticket_tickets 
WHERE contact_id IS NOT NULL
ON CONFLICT (ticket_id, contact_id) DO NOTHING;

-- Kommentar på tabellen
COMMENT ON TABLE tticket_contacts IS 'Many-to-many relation mellem tickets og contacts med roller';
COMMENT ON COLUMN tticket_contacts.role IS 'Kontaktens rolle: primary (hovedkontakt), cc (carbon copy), observer (følger med), assignee (assigned kontakt), requester (oprindelig anmoder)';

-- Views til at få kontakter grouped by role
CREATE OR REPLACE VIEW vw_tticket_contacts_summary AS
SELECT 
    t.id as ticket_id,
    t.ticket_number,
    json_agg(
        json_build_object(
            'contact_id', c.id,
            'first_name', c.first_name,
            'last_name', c.last_name,
            'email', c.email,
            'phone', c.phone,
            'role', tc.role,
            'added_at', tc.added_at
        ) ORDER BY 
            CASE tc.role
                WHEN 'primary' THEN 1
                WHEN 'requester' THEN 2
                WHEN 'assignee' THEN 3
                WHEN 'cc' THEN 4
                WHEN 'observer' THEN 5
                ELSE 6
            END,
            tc.added_at
    ) as contacts
FROM tticket_tickets t
LEFT JOIN tticket_contacts tc ON t.id = tc.ticket_id
LEFT JOIN contacts c ON tc.contact_id = c.id
GROUP BY t.id, t.ticket_number;

COMMENT ON VIEW vw_tticket_contacts_summary IS 'Oversigt over alle kontakter per ticket med roller, sorteret efter rolle prioritet';
