/**
 * Admin tenant provisioning auth tests — S2-001 regression.
 *
 * Verifies POST /api/admin/tenants/provision rejects unauthenticated requests.
 */
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { Hono } from 'hono'

vi.mock('@zync/auth', () => {
  const passthrough = () => async (_c: unknown, next: () => Promise<void>) => next()
  return {
    hashPassword: vi.fn().mockResolvedValue('hashed'),
    requireAdminPermission: vi.fn(passthrough),
    requireAdminSession: vi.fn(passthrough),
    requirePermission: vi.fn(passthrough),
    requireTier: vi.fn(passthrough),
    verifyAdminSession: vi.fn(),
  }
})

vi.mock('@zync/db/queries', () => ({
  createDb: vi.fn(() => ({})),
  findAdminWithPermissions: vi.fn(),
  findUserByEmail: vi.fn(),
  createPendingUser: vi.fn(),
  completeEmailVerification: vi.fn(),
  createFreelancerSubscription: vi.fn(),
}))

import { adminProvisionTenantRoute } from '../src/routes/admin/provision-tenant'
import type { AppEnv } from '../src/types'

const mockEnv = {
  DB: { connectionString: 'postgresql://test:test@localhost/test' },
  JWT_SECRET: 'test-jwt-secret',
} as AppEnv['Bindings']

function appWithProvisionRoute() {
  const app = new Hono<AppEnv>()
  app.route('/api/admin/tenants', adminProvisionTenantRoute)
  return app
}

describe('POST /api/admin/tenants/provision auth (S2-001)', () => {
  beforeEach(() => {
    vi.clearAllMocks()
  })

  it('returns 401 when no admin session cookie is present', async () => {
    const res = await appWithProvisionRoute().request('/api/admin/tenants/provision', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Origin: 'https://admin.zync.is',
      },
      body: JSON.stringify({
        tenantName: 'Test Tenant',
        ownerEmail: 'owner@example.com',
        ownerPassword: 'password123',
      }),
    })

    expect(res.status).toBe(401)
    const body = (await res.json()) as { error: string }
    expect(body.error).toBe('Unauthorized')
  })

  it('returns 403 for mutating requests without an allowed Origin', async () => {
    const res = await appWithProvisionRoute().request('/api/admin/tenants/provision', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        tenantName: 'Test Tenant',
        ownerEmail: 'owner@example.com',
        ownerPassword: 'password123',
      }),
    })

    expect(res.status).toBe(403)
    const body = (await res.json()) as { error: string }
    expect(body.error).toBe('Forbidden: invalid Origin')
  })
})
