begin;
select plan(25); -- Total number of tests (reduced - removed 4 FK tests that don't exist)

-- ============================================================================
-- RLS Enabled Tests
-- ============================================================================

SELECT is(
    (SELECT relrowsecurity FROM pg_class WHERE relname = 'feedbacks' AND relnamespace = 'public'::regnamespace),
    true,
    'RLS should be enabled on feedbacks table'
);

SELECT is(
    (SELECT relrowsecurity FROM pg_class WHERE relname = 'events' AND relnamespace = 'public'::regnamespace),
    true,
    'RLS should be enabled on events table'
);

-- ============================================================================
-- Feedbacks Table RLS Policies
-- ============================================================================

SELECT ok(
    (SELECT COUNT(*) FROM pg_policies WHERE tablename = 'feedbacks' AND policyname = 'Users can insert feedback.') > 0,
    'Policy for inserting feedback should exist'
);

SELECT is(
    (SELECT cmd FROM pg_policies WHERE tablename = 'feedbacks' AND policyname = 'Users can insert feedback.' LIMIT 1),
    'INSERT',
    'Feedback policy should be for INSERT'
);

SELECT ok(
    (SELECT COALESCE('authenticated' = ANY(roles), false) FROM pg_policies WHERE tablename = 'feedbacks' AND policyname = 'Users can insert feedback.' LIMIT 1),
    'Feedback insert policy should apply to authenticated users'
);

-- ============================================================================
-- Events Table RLS Policies
-- ============================================================================

SELECT ok(
    (SELECT COUNT(*) FROM pg_policies WHERE tablename = 'events' AND policyname = 'Users can view events from accessible tablos') > 0,
    'Policy for viewing events from accessible tablos should exist'
);

SELECT ok(
    (SELECT COUNT(*) FROM pg_policies WHERE tablename = 'events' AND policyname = 'Users can insert events into accessible tablos') > 0,
    'Policy for inserting events should exist'
);

SELECT ok(
    (SELECT COUNT(*) FROM pg_policies WHERE tablename = 'events' AND policyname = 'Users can update their own events in accessible tablos') > 0,
    'Policy for updating own events should exist'
);

-- Test policy commands
SELECT is(
    (SELECT cmd FROM pg_policies WHERE tablename = 'events' AND policyname = 'Users can view events from accessible tablos' LIMIT 1),
    'SELECT',
    'View events policy should be for SELECT'
);

SELECT is(
    (SELECT cmd FROM pg_policies WHERE tablename = 'events' AND policyname = 'Users can insert events into accessible tablos' LIMIT 1),
    'INSERT',
    'Insert events policy should be for INSERT'
);

SELECT is(
    (SELECT cmd FROM pg_policies WHERE tablename = 'events' AND policyname = 'Users can update their own events in accessible tablos' LIMIT 1),
    'UPDATE',
    'Update events policy should be for UPDATE'
);

-- Test policy roles
SELECT ok(
    (SELECT COALESCE('authenticated' = ANY(roles), false) FROM pg_policies WHERE tablename = 'events' AND policyname = 'Users can view events from accessible tablos' LIMIT 1),
    'View events policy should apply to authenticated users'
);

SELECT ok(
    (SELECT COALESCE('authenticated' = ANY(roles), false) FROM pg_policies WHERE tablename = 'events' AND policyname = 'Users can insert events into accessible tablos' LIMIT 1),
    'Insert events policy should apply to authenticated users'
);

-- ============================================================================
-- Feedbacks Behavior Tests
-- ============================================================================

-- Create test user and feedback
DO $$
DECLARE
    feedback_user_id uuid := gen_random_uuid();
BEGIN
    -- Insert test user
    INSERT INTO auth.users (id, instance_id, aud, role, email, encrypted_password, email_confirmed_at, created_at, updated_at)
    VALUES 
        (feedback_user_id, '00000000-0000-0000-0000-000000000000', 'authenticated', 'authenticated', 'feedbackuser_' || feedback_user_id::text || '@test.com', 'encrypted', now(), now(), now())
    ON CONFLICT DO NOTHING;
    
    -- Insert test profile
    INSERT INTO public.profiles (id, email, first_name, last_name, short_user_id)
    VALUES 
        (feedback_user_id, 'feedbackuser_' || feedback_user_id::text || '@test.com', 'Feedback', 'User', substring(feedback_user_id::text from 1 for 8))
    ON CONFLICT DO NOTHING;
    
    -- Insert test feedback
    INSERT INTO public.feedbacks (fd_type, user_id, message)
    VALUES 
        ('bug', feedback_user_id, 'Test bug report'),
        ('feature', feedback_user_id, 'Test feature request');
    
    -- Store test ID
    PERFORM set_config('test.feedback_user_id', feedback_user_id::text, true);
END $$;

-- Test: Verify feedbacks were created
SELECT is(
    (SELECT count(*)::integer FROM public.feedbacks WHERE user_id = current_setting('test.feedback_user_id')::uuid),
    2,
    'Both test feedbacks should be created'
);

-- Test: Verify feedback types are correct
SELECT ok(
    (SELECT fd_type FROM public.feedbacks WHERE message = 'Test bug report' LIMIT 1) = 'bug',
    'Bug feedback should have correct type'
);

SELECT ok(
    (SELECT fd_type FROM public.feedbacks WHERE message = 'Test feature request' LIMIT 1) = 'feature',
    'Feature feedback should have correct type'
);

-- ============================================================================
-- Events Behavior Tests
-- ============================================================================

-- Create test user, tablo, and event
DO $$
DECLARE
    event_user_id uuid := gen_random_uuid();
    event_tablo_id text;
BEGIN
    -- Insert test user
    INSERT INTO auth.users (id, instance_id, aud, role, email, encrypted_password, email_confirmed_at, created_at, updated_at)
    VALUES 
        (event_user_id, '00000000-0000-0000-0000-000000000000', 'authenticated', 'authenticated', 'eventuser_' || event_user_id::text || '@test.com', 'encrypted', now(), now(), now())
    ON CONFLICT DO NOTHING;
    
    -- Insert test profile
    INSERT INTO public.profiles (id, email, first_name, last_name, short_user_id)
    VALUES 
        (event_user_id, 'eventuser_' || event_user_id::text || '@test.com', 'Event', 'User', substring(event_user_id::text from 1 for 8))
    ON CONFLICT DO NOTHING;
    
    -- Insert test tablo
    INSERT INTO public.tablos (owner_id, name, status, position)
    VALUES 
        (event_user_id, 'Event Test Tablo', 'todo', 0)
    RETURNING id::text INTO event_tablo_id;
    
    -- Insert test event
    INSERT INTO public.events (tablo_id, title, description, start_date, start_time, created_by)
    VALUES 
        (event_tablo_id, 'Test Event', 'Test event description', '2025-12-01', '10:00', event_user_id);
    
    -- Store test IDs
    PERFORM set_config('test.event_user_id', event_user_id::text, true);
    PERFORM set_config('test.event_tablo_id', event_tablo_id, true);
END $$;

-- Test: Verify event was created
SELECT ok(
    (SELECT count(*) FROM public.events WHERE title = 'Test Event' AND deleted_at IS NULL) > 0,
    'Test event should be created'
);

-- Test: Verify event is linked to correct tablo
SELECT is(
    (SELECT tablo_id FROM public.events WHERE title = 'Test Event' AND deleted_at IS NULL LIMIT 1),
    current_setting('test.event_tablo_id'),
    'Event should be linked to correct tablo'
);

-- Test: Verify event has correct creator
SELECT is(
    (SELECT created_by FROM public.events WHERE title = 'Test Event' AND deleted_at IS NULL LIMIT 1),
    current_setting('test.event_user_id')::uuid,
    'Event should have correct creator'
);

-- ============================================================================
-- Check Constraint Tests
-- ============================================================================

-- Test feedbacks fd_type check constraint
SELECT ok(
    (SELECT COUNT(*) FROM information_schema.check_constraints 
     WHERE constraint_schema = 'public' 
     AND constraint_name LIKE '%feedbacks_fd_type%') > 0,
    'Feedbacks table should have fd_type check constraint'
);

-- Test that invalid feedback type would be rejected (we can't actually insert invalid data, but we can check the constraint exists)
SELECT col_has_check('public', 'feedbacks', 'fd_type',
    'fd_type column should have check constraint');

-- Test tablos status check constraint
SELECT col_has_check('public', 'tablos', 'status',
    'status column should have check constraint');

-- ============================================================================
-- Foreign Key Constraints Tests
-- ============================================================================

-- Note: feedbacks table doesn't have explicit foreign key constraints in the schema
SELECT has_fk('public', 'events', 'events should have foreign key constraints');

-- Test that events.tablo_id references tablos.id
SELECT fk_ok(
    'public', 'events', 'tablo_id',
    'public', 'tablos', 'id',
    'events.tablo_id should reference tablos.id'
);

-- Test that events.created_by references auth.users.id
SELECT fk_ok(
    'public', 'events', 'created_by',
    'auth', 'users', 'id',
    'events.created_by should reference auth.users.id'
);

select * from finish();
rollback;

