-- ============================================================================
-- Seed Data for LOAF Membership Platform
-- Run this after creating the database schema
-- ============================================================================

BEGIN;

-- ============================================================================
-- STEP 1: Create Default Roles
-- ============================================================================

INSERT INTO roles (id, code, name, description, is_system_role, created_at, updated_at)
VALUES
    (gen_random_uuid(), 'guest', 'Guest', 'Default role for new registrations', true, NOW(), NOW()),
    (gen_random_uuid(), 'member', 'Member', 'Active paying members with full access', true, NOW(), NOW()),
    (gen_random_uuid(), 'admin', 'Admin', 'Board members with management access', true, NOW(), NOW()),
    (gen_random_uuid(), 'finance', 'Finance', 'Treasurer role with financial access', true, NOW(), NOW()),
    (gen_random_uuid(), 'superadmin', 'Super Admin', 'Full system access', true, NOW(), NOW())
ON CONFLICT (code) DO NOTHING;

-- ============================================================================
-- STEP 2: Create Permissions
-- ============================================================================

INSERT INTO permissions (id, code, name, description, module, created_at)
VALUES
    -- User Management Permissions
    (gen_random_uuid(), 'users.view', 'View Users', 'View user list and profiles', 'users', NOW()),
    (gen_random_uuid(), 'users.create', 'Create Users', 'Create new users', 'users', NOW()),
    (gen_random_uuid(), 'users.edit', 'Edit Users', 'Edit user information', 'users', NOW()),
    (gen_random_uuid(), 'users.delete', 'Delete Users', 'Delete users', 'users', NOW()),
    (gen_random_uuid(), 'users.approve', 'Approve Users', 'Approve pending memberships', 'users', NOW()),
    (gen_random_uuid(), 'users.import', 'Import Users', 'Import users from CSV/external sources', 'users', NOW()),

    -- Event Management Permissions
    (gen_random_uuid(), 'events.view', 'View Events', 'View event list and details', 'events', NOW()),
    (gen_random_uuid(), 'events.create', 'Create Events', 'Create new events', 'events', NOW()),
    (gen_random_uuid(), 'events.edit', 'Edit Events', 'Edit event information', 'events', NOW()),
    (gen_random_uuid(), 'events.delete', 'Delete Events', 'Delete events', 'events', NOW()),
    (gen_random_uuid(), 'events.publish', 'Publish Events', 'Publish/unpublish events', 'events', NOW()),
    (gen_random_uuid(), 'events.manage_attendance', 'Manage Attendance', 'Mark event attendance', 'events', NOW()),

    -- Financial Permissions
    (gen_random_uuid(), 'finance.view', 'View Financial Data', 'View subscriptions and payments', 'finance', NOW()),
    (gen_random_uuid(), 'finance.manage_plans', 'Manage Subscription Plans', 'Create/edit subscription plans', 'finance', NOW()),
    (gen_random_uuid(), 'finance.manage_subscriptions', 'Manage Subscriptions', 'Manage user subscriptions', 'finance', NOW()),
    (gen_random_uuid(), 'finance.view_reports', 'View Financial Reports', 'Access financial reports', 'finance', NOW()),
    (gen_random_uuid(), 'finance.export', 'Export Financial Data', 'Export financial data', 'finance', NOW()),

    -- Content Management Permissions
    (gen_random_uuid(), 'content.newsletters', 'Manage Newsletters', 'Manage newsletter archives', 'content', NOW()),
    (gen_random_uuid(), 'content.documents', 'Manage Documents', 'Manage bylaws and documents', 'content', NOW()),
    (gen_random_uuid(), 'content.gallery', 'Manage Gallery', 'Manage event galleries', 'content', NOW()),

    -- System Permissions
    (gen_random_uuid(), 'system.settings', 'System Settings', 'Manage system settings', 'system', NOW()),
    (gen_random_uuid(), 'system.roles', 'Manage Roles', 'Create/edit roles and permissions', 'system', NOW()),
    (gen_random_uuid(), 'system.invitations', 'Manage Invitations', 'Send admin invitations', 'system', NOW()),
    (gen_random_uuid(), 'system.storage', 'Manage Storage', 'View storage usage', 'system', NOW()),
    (gen_random_uuid(), 'system.audit', 'View Audit Logs', 'View system audit logs', 'system', NOW())
ON CONFLICT (code) DO NOTHING;

-- ============================================================================
-- STEP 3: Assign Permissions to Roles
-- ============================================================================

-- Guest Role: No permissions (view-only through public pages)
-- No entries needed

-- Member Role: Limited permissions
INSERT INTO role_permissions (id, role, role_id, permission_id, created_at)
SELECT
    gen_random_uuid(),
    'member',
    (SELECT id FROM roles WHERE code = 'member'),
    p.id,
    NOW()
FROM permissions p
WHERE p.code IN (
    'events.view'
)
ON CONFLICT DO NOTHING;

-- Admin Role: Most permissions except financial
INSERT INTO role_permissions (id, role, role_id, permission_id, created_at)
SELECT
    gen_random_uuid(),
    'admin',
    (SELECT id FROM roles WHERE code = 'admin'),
    p.id,
    NOW()
FROM permissions p
WHERE p.code IN (
    -- User Management
    'users.view', 'users.create', 'users.edit', 'users.approve', 'users.import',
    -- Event Management
    'events.view', 'events.create', 'events.edit', 'events.delete', 'events.publish', 'events.manage_attendance',
    -- Content Management
    'content.newsletters', 'content.documents', 'content.gallery',
    -- System (limited)
    'system.invitations', 'system.storage'
)
ON CONFLICT DO NOTHING;

-- Finance Role: Financial permissions + basic access
INSERT INTO role_permissions (id, role, role_id, permission_id, created_at)
SELECT
    gen_random_uuid(),
    'finance',
    (SELECT id FROM roles WHERE code = 'finance'),
    p.id,
    NOW()
FROM permissions p
WHERE p.code IN (
    -- Financial
    'finance.view', 'finance.manage_plans', 'finance.manage_subscriptions', 'finance.view_reports', 'finance.export',
    -- Basic Access
    'users.view', 'events.view'
)
ON CONFLICT DO NOTHING;

-- Superadmin Role: All permissions
INSERT INTO role_permissions (id, role, role_id, permission_id, created_at)
SELECT
    gen_random_uuid(),
    'superadmin',
    (SELECT id FROM roles WHERE code = 'superadmin'),
    p.id,
    NOW()
FROM permissions p
ON CONFLICT DO NOTHING;

-- ============================================================================
-- STEP 4: Create Subscription Plans
-- ============================================================================

INSERT INTO subscription_plans (id, name, description, price_cents, billing_cycle, custom_cycle_enabled, minimum_price_cents, allow_donation, is_active, created_at, updated_at)
VALUES
    -- Annual Individual Membership
    (
        gen_random_uuid(),
        'Annual Individual Membership',
        'Standard annual membership for one person. Includes access to all LOAF events, member directory, and exclusive content.',
        6000,  -- $60.00
        'annual',
        false,
        6000,
        false,
        true,
        NOW(),
        NOW()
    ),

    -- Annual Group Membership
    (
        gen_random_uuid(),
        'Annual Group Membership',
        'Annual membership for two people living at the same address. Both members receive full access to all LOAF benefits.',
        10000,  -- $100.00
        'annual',
        false,
        10000,
        false,
        true,
        NOW(),
        NOW()
    ),

    -- Pay What You Want (with minimum)
    (
        gen_random_uuid(),
        'Pay What You Want Membership',
        'Choose your own annual membership amount. Minimum $30. Additional contributions help support our scholarship fund.',
        3000,  -- $30.00 minimum
        'annual',
        true,  -- Allow custom amount
        3000,  -- Minimum $30
        true,  -- Additional amount is treated as donation
        true,
        NOW(),
        NOW()
    )
ON CONFLICT DO NOTHING;

-- ============================================================================
-- STEP 5: Initialize Storage Usage (if not already done)
-- ============================================================================

INSERT INTO storage_usage (id, total_bytes_used, max_bytes_allowed, last_calculated_at, created_at, updated_at)
VALUES (gen_random_uuid(), 0, 107374182400, NOW(), NOW(), NOW())  -- 100GB limit
ON CONFLICT DO NOTHING;

COMMIT;

-- ============================================================================
-- Success Message
-- ============================================================================

\echo '✅ Seed data created successfully!'
\echo ''
\echo 'Created:'
\echo '  - 5 default roles (guest, member, admin, finance, superadmin)'
\echo '  - 25 permissions across 5 modules'
\echo '  - Role-permission mappings'
\echo '  - 3 subscription plans'
\echo '  - Storage usage initialization'
\echo ''
\echo 'Next steps:'
\echo '  1. Create superadmin user (see instructions below)'
\echo '  2. Configure Stripe price IDs in subscription_plans'
\echo '  3. Start the application'
\echo ''
\echo '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'
\echo 'CREATE SUPERADMIN USER:'
\echo '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'
\echo ''
\echo 'Generate password hash in Python:'
\echo '  python3 -c "import bcrypt; print(bcrypt.hashpw(b\"your-password\", bcrypt.gensalt()).decode())"'
\echo ''
\echo 'Then run:'
\echo '  psql -U postgres -d loaf_new'
\echo ''
\echo 'INSERT INTO users ('
\echo '    id, email, password_hash, first_name, last_name,'
\echo '    status, role, email_verified, created_at, updated_at'
\echo ') VALUES ('
\echo '    gen_random_uuid(),'
\echo '    '\''admin@loafmembers.org'\'','
\echo '    '\''$2b$12$YOUR_BCRYPT_HASH_HERE'\'','
\echo '    '\''Admin'\'','
\echo '    '\''User'\'','
\echo '    '\''active'\'','
\echo '    '\''superadmin'\'','
\echo '    true,'
\echo '    NOW(),'
\echo '    NOW()'
\echo ');'
\echo ''
