-- Add kiosk PIN system to events table
ALTER TABLE events ADD COLUMN IF NOT EXISTS kiosk_pin VARCHAR(4);
ALTER TABLE events ADD COLUMN IF NOT EXISTS kiosk_pin_created_at TIMESTAMP WITH TIME ZONE;
ALTER TABLE events ADD COLUMN IF NOT EXISTS kiosk_pin_created_by UUID REFERENCES auth.users(id);

-- Add kiosk access logs table
CREATE TABLE IF NOT EXISTS kiosk_access_logs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    event_id UUID NOT NULL REFERENCES events(id) ON DELETE CASCADE,
    accessed_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    ip_address INET,
    user_agent TEXT,
    success BOOLEAN DEFAULT true,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Add RLS policies for kiosk access logs
ALTER TABLE kiosk_access_logs ENABLE ROW LEVEL SECURITY;

-- Allow users to view logs for their organization's events
CREATE POLICY "Users can view kiosk logs for their organization events" ON kiosk_access_logs
    FOR SELECT
    TO authenticated
    USING (
        event_id IN (
            SELECT e.id FROM events e
            JOIN users u ON e.organization_id = u.organization_id
            WHERE u.id = auth.uid()
        )
    );

-- Allow users to insert logs for their organization's events
CREATE POLICY "Users can insert kiosk logs for their organization events" ON kiosk_access_logs
    FOR INSERT
    TO authenticated
    WITH CHECK (
        event_id IN (
            SELECT e.id FROM events e
            JOIN users u ON e.organization_id = u.organization_id
            WHERE u.id = auth.uid()
        )
    );

-- Add index for performance
CREATE INDEX IF NOT EXISTS idx_kiosk_access_logs_event_id ON kiosk_access_logs(event_id);
CREATE INDEX IF NOT EXISTS idx_kiosk_access_logs_accessed_at ON kiosk_access_logs(accessed_at);