import { createClient } from '@supabase/supabase-js' const action = process.argv[2] const url = process.env.D3RO_LOCAL_SUPABASE_URL?.trim() ?? '' const serviceRoleKey = process.env.D3RO_LOCAL_SUPABASE_SERVICE_ROLE_KEY?.trim() ?? '' if (!url.startsWith('http://127.0.0.1:55321') || serviceRoleKey.length < 20) { throw new Error('D3RO local Supabase service credentials are required') } const client = createClient(url, serviceRoleKey, { auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false } }) const adminEmail = 'admin.browser.e2e@example.com' const targetEmail = 'customer.browser.e2e@example.com' async function matchingUsers() { const { data, error } = await client.auth.admin.listUsers({ page: 1, perPage: 1000 }) if (error) throw error return data.users.filter((user) => user.email === adminEmail || user.email === targetEmail) } async function cleanup() { const users = await matchingUsers() const ids = users.map((user) => user.id) if (ids.length === 0) return await client.from('audit_log').delete().in('admin_id', ids) await client.from('admin_operation_requests').delete().in('actor_id', ids) for (const user of users) await client.auth.admin.deleteUser(user.id) } if (action === 'cleanup') { await cleanup() console.log('admin browser fixture cleaned') } else if (action === 'setup') { await cleanup() const admin = await client.auth.admin.createUser({ email: adminEmail, password: 'Admin-browser-e2e-strong-password!', email_confirm: true, app_metadata: { role: 'super_admin' }, user_metadata: { name: 'Browser E2E Admin' } }) if (admin.error) throw admin.error const target = await client.auth.admin.createUser({ email: targetEmail, password: 'Customer-browser-e2e-strong-password!', email_confirm: true, app_metadata: { role: 'user' }, user_metadata: { name: 'Browser E2E Customer' } }) if (target.error) throw target.error const roleUpdate = await client.from('profiles').update({ role: 'super_admin' }).eq('id', admin.data.user.id) if (roleUpdate.error) throw roleUpdate.error console.log(`admin browser fixture ready target=${target.data.user.id}`) } else { throw new Error('Expected setup or cleanup') }