import { describe, expect, it, vi } from 'vitest'

vi.mock('jsonwebtoken', () => ({ default: { verify: vi.fn(() => ({ sub: 'admin_1', type: 'admin' })) } }))
vi.mock('../../lib/redis', () => ({
  redis: { on: vi.fn(), get: vi.fn(), set: vi.fn(), del: vi.fn(), quit: vi.fn() },
}))
vi.mock('../../lib/prisma', () => ({
  prisma: {
    adminUser: { findUnique: vi.fn().mockResolvedValue({ id: 'admin_1', role: 'FINANCE', isActive: true, totpEnabled: true }) },
  },
}))
vi.mock('../../modules/admin/admin.service', () => ({
  getBilling: vi.fn(),
  getInvoicePdf: vi.fn(),
  updateBillingAccount: vi.fn(),
  createBillingInvoice: vi.fn(),
  finalizeBillingInvoice: vi.fn(),
}))

import request from 'supertest'
import { createApp } from '../../app'
import * as adminService from '../../modules/admin/admin.service'

process.env.JWT_SECRET = 'test-secret'
const app = createApp()

describe('admin billing e2e boundaries', () => {
  it('rejects anonymous billing access and malformed invoice creation without touching services', async () => {
    const anonymous = await request(app).get('/api/v1/admin/billing')
    expect(anonymous.status).toBe(401)
    expect(adminService.getBilling).not.toHaveBeenCalled()

    const malformed = await request(app)
      .post('/api/v1/admin/billing/accounts/billing_account_1/invoices')
      .set('Authorization', 'Bearer admin-token')
      .send({ invoiceType: 'MADE_UP', lineItems: [{ quantity: 0, unitAmount: 100 }] })

    expect(malformed.status).toBe(400)
    expect(adminService.createBillingInvoice).not.toHaveBeenCalled()
  })
})
