import { beforeEach, describe, expect, it, vi } from 'vitest'
import { Hono } from 'hono'

const { listTenantsAdmin } = vi.hoisted(() => ({
  listTenantsAdmin: vi.fn().mockResolvedValue({
    items: [],
    total: 0,
    page: 1,
    limit: 50,
  }),
}))

vi.mock('@zync/db/queries', () => ({
  createDb: vi.fn(() => ({})),
  listTenantsAdmin,
  getTenantDetailAdmin: vi.fn(),
}))

vi.mock('../src/middleware/admin-auth', () => ({
  adminAuthMiddleware: async (c: { set: (key: string, value: unknown) => void }, next: () => Promise<void>) => {
    c.set('session', {
      sub: 'admin-1',
      type: 'admin',
      totp_verified: true,
      role: 'SUPER_ADMIN',
      permissions: ['admin.tenants:read'],
    })
    await next()
  },
}))

vi.mock('../src/middleware/guards', () => ({
  requireAdminSession: () => async (_c: unknown, next: () => Promise<void>) => next(),
}))

import { adminTenantsRoutes } from '../src/routes/admin/tenants'
import type { AppEnv } from '../src/types'

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

describe('GET /api/admin/tenants query contract', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    listTenantsAdmin.mockResolvedValue({
      items: [],
      total: 0,
      page: 1,
      limit: 50,
    })
  })

  it('accepts status sorting and filtering required by the spec', async () => {
    const res = await appWithRoute().request(
      '/api/admin/tenants?status=active&sort=status&order=asc&page=2&limit=25',
    )

    expect(res.status).toBe(200)
    expect(listTenantsAdmin).toHaveBeenCalledWith(
      {},
      expect.objectContaining({
        status: 'active',
        sort: 'status',
        order: 'asc',
        page: 2,
        limit: 25,
      }),
    )
  })
})
