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

vi.mock('../../lib/prisma', () => ({
  prisma: {
    adminUser: { findFirst: vi.fn(), findUniqueOrThrow: vi.fn(), update: vi.fn() },
    auditLog: { create: vi.fn() },
    company: { findMany: vi.fn(), count: vi.fn(), findUniqueOrThrow: vi.fn(), update: vi.fn(), delete: vi.fn() },
    billingAccount: { findMany: vi.fn(), count: vi.fn() },
    $transaction: vi.fn(),
  },
}))

import { prisma } from '../../lib/prisma'
import * as repo from './admin.repo'

describe('admin.repo edge queries', () => {
  beforeEach(() => vi.clearAllMocks())

  it('clears reset token metadata when updating an admin password', async () => {
    await repo.updateAdminPassword('admin_1', 'hash_1')

    expect(prisma.adminUser.update).toHaveBeenCalledWith({
      where: { id: 'admin_1' },
      data: {
        passwordHash: 'hash_1',
        passwordResetToken: null,
        passwordResetExpiresAt: null,
      },
    })
  })

  it('filters company list by search, status and plan with pagination', async () => {
    vi.mocked(prisma.company.findMany).mockResolvedValue([] as never)
    vi.mocked(prisma.company.count).mockResolvedValue(0 as never)

    await repo.listCompaniesPage({ q: 'atlas', status: 'ACTIVE', plan: 'PRO', page: 3, pageSize: 25 })

    const where = {
      status: 'ACTIVE',
      OR: [
        { name: { contains: 'atlas', mode: 'insensitive' } },
        { email: { contains: 'atlas', mode: 'insensitive' } },
        { slug: { contains: 'atlas', mode: 'insensitive' } },
      ],
      subscription: { plan: 'PRO' },
    }

    expect(prisma.company.findMany).toHaveBeenCalledWith(expect.objectContaining({
      where,
      skip: 50,
      take: 25,
      orderBy: { createdAt: 'desc' },
    }))
    expect(prisma.company.count).toHaveBeenCalledWith({ where })
  })

  it('looks up reset tokens only when they have not expired', async () => {
    vi.useFakeTimers()
    vi.setSystemTime(new Date('2026-06-01T00:00:00.000Z'))

    await repo.findAdminByResetToken('reset-token')

    expect(prisma.adminUser.findFirst).toHaveBeenCalledWith({
      where: {
        passwordResetToken: 'reset-token',
        passwordResetExpiresAt: { gt: new Date('2026-06-01T00:00:00.000Z') },
      },
    })

    vi.useRealTimers()
  })
})
