import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createFakeSupabase } from './stubs/fake-supabase'

const db = createFakeSupabase()
const trips = vi.hoisted(() => ({ getVisibleTrips: vi.fn() }))
vi.mock('@/lib/supabase/admin', () => ({ createAdminClient: () => db }))
vi.mock('@/lib/data/trips', () => ({ getVisibleTrips: trips.getVisibleTrips }))

const { loadRoutePurchases } = await import('@/lib/data/billing')

const buyerId = 'buyer-1'
const buyer = { id: buyerId, email: 'buyer@example.test', role: 'admin' } as never
const trip = { id: 'trip-1', origin: 'Austin, TX', destination: 'Dallas, TX' }

beforeEach(() => {
  db.reset()
  trips.getVisibleTrips.mockResolvedValue({ trips: [trip], warnings: [] })
})

describe('Billing & Wallet purchase history', () => {
  it('shows only route requests created by the current buyer, even on a visible trip', async () => {
    db.seed('service_requests', [
      { id: 'mine', trip_id: trip.id, type: 'route_request', requested_by: buyerId, requester_label: 'Buyer', state_code: 'TX', status: 'requested', route_type: 'express' },
      { id: 'other', trip_id: trip.id, type: 'route_request', requested_by: 'someone-else', requester_label: 'Someone else', state_code: 'TX', status: 'requested', route_type: 'express' },
    ])

    await expect(loadRoutePurchases(buyer)).resolves.toEqual([
      expect.objectContaining({ id: 'mine', requester_label: 'Buyer', trip_label: 'Austin, TX → Dallas, TX' }),
    ])
  })
})
