-- ==========================================================================
-- Migration 097: Archived Tickets (Simply-CRM import)
-- ==========================================================================

CREATE TABLE IF NOT EXISTS tticket_archived_tickets (
    id SERIAL PRIMARY KEY,
    source_system VARCHAR(50) NOT NULL DEFAULT 'simplycrm',
    external_id VARCHAR(100) NOT NULL,
    ticket_number VARCHAR(100),
    title VARCHAR(500),
    organization_name VARCHAR(255),
    contact_name VARCHAR(255),
    email_from VARCHAR(255),
    time_spent_hours DECIMAL(10,2),
    description TEXT,
    solution TEXT,
    status VARCHAR(50),
    priority VARCHAR(50),
    source_created_at TIMESTAMP,
    source_updated_at TIMESTAMP,
    imported_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    last_synced_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    sync_hash VARCHAR(64),
    raw_data JSONB DEFAULT '{}'::jsonb,
    UNIQUE (source_system, external_id)
);

CREATE INDEX IF NOT EXISTS idx_tticket_archived_external ON tticket_archived_tickets(source_system, external_id);
CREATE INDEX IF NOT EXISTS idx_tticket_archived_ticket_number ON tticket_archived_tickets(ticket_number);
CREATE INDEX IF NOT EXISTS idx_tticket_archived_org ON tticket_archived_tickets(organization_name);
CREATE INDEX IF NOT EXISTS idx_tticket_archived_created ON tticket_archived_tickets(source_created_at DESC);

CREATE TABLE IF NOT EXISTS tticket_archived_messages (
    id SERIAL PRIMARY KEY,
    archived_ticket_id INTEGER NOT NULL REFERENCES tticket_archived_tickets(id) ON DELETE CASCADE,
    message_type VARCHAR(50) NOT NULL,
    subject VARCHAR(500),
    body TEXT,
    author_name VARCHAR(255),
    author_email VARCHAR(255),
    source_created_at TIMESTAMP,
    imported_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    raw_data JSONB DEFAULT '{}'::jsonb
);

CREATE INDEX IF NOT EXISTS idx_tticket_archived_messages_ticket ON tticket_archived_messages(archived_ticket_id);
CREATE INDEX IF NOT EXISTS idx_tticket_archived_messages_type ON tticket_archived_messages(message_type);
CREATE INDEX IF NOT EXISTS idx_tticket_archived_messages_created ON tticket_archived_messages(source_created_at DESC);
