-- Migration: Create tickets table v2 (with company_id) - uses UUID v7
-- Description: Stores support tickets from users/companies

-- Skip if tickets table already exists with different schema
-- Add company_id column to existing tickets table if not exists
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'tickets') THEN
        -- Add company_id column if not exists
        IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'tickets' AND column_name = 'company_id') THEN
            ALTER TABLE tickets ADD COLUMN company_id UUID REFERENCES companies(id) ON DELETE SET NULL;
        END IF;
        -- Add description column if not exists
        IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'tickets' AND column_name = 'description') THEN
            ALTER TABLE tickets ADD COLUMN description TEXT;
        END IF;
        -- Add category column if not exists
        IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'tickets' AND column_name = 'category') THEN
            ALTER TABLE tickets ADD COLUMN category VARCHAR(50) DEFAULT 'general';
        END IF;
        -- Add priority column if not exists
        IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'tickets' AND column_name = 'priority') THEN
            ALTER TABLE tickets ADD COLUMN priority VARCHAR(20) DEFAULT 'medium';
        END IF;
        -- Add assigned_to column if not exists
        IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'tickets' AND column_name = 'assigned_to') THEN
            ALTER TABLE tickets ADD COLUMN assigned_to UUID REFERENCES users(id) ON DELETE SET NULL;
        END IF;
        -- Add resolved_at column if not exists
        IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'tickets' AND column_name = 'resolved_at') THEN
            ALTER TABLE tickets ADD COLUMN resolved_at TIMESTAMP;
        END IF;
    END IF;
END $$;

-- Create ticket_messages table if not exists (with UUID v7)
CREATE TABLE IF NOT EXISTS ticket_messages (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v7(),
    ticket_id UUID NOT NULL REFERENCES tickets(id) ON DELETE CASCADE,
    user_id UUID REFERENCES users(id) ON DELETE SET NULL,
    message TEXT NOT NULL,
    is_internal BOOLEAN DEFAULT false,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Create indexes if not exists
CREATE INDEX IF NOT EXISTS idx_tickets_company ON tickets(company_id);
CREATE INDEX IF NOT EXISTS idx_ticket_messages_ticket ON ticket_messages(ticket_id);

COMMENT ON TABLE tickets IS 'Support tickets from users and companies';
COMMENT ON TABLE ticket_messages IS 'Messages/replies within a support ticket';
