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

const prismaMock = vi.hoisted(() => ({
  employee: {
    findUnique: vi.fn(),
    findFirst: vi.fn(),
    update: vi.fn(),
  },
}))

vi.mock('../../lib/prisma', () => ({ prisma: prismaMock }))

import * as repo from './auth.employee.repo'

describe('auth.employee.repo query boundaries', () => {
  it('loads employee sessions with company context by id', async () => {
    await repo.findEmployeeWithCompanyById('employee_1')

    expect(prismaMock.employee.findUnique).toHaveBeenCalledWith({
      where: { id: 'employee_1' },
      include: { company: true },
    })
  })

  it('looks up employee login emails case-insensitively and includes company context', async () => {
    await repo.findEmployeeWithCompanyByEmail('Agent@Example.TEST')

    expect(prismaMock.employee.findFirst).toHaveBeenCalledWith({
      where: { email: { equals: 'Agent@Example.TEST', mode: 'insensitive' } },
      include: { company: true },
    })
  })

  it('only sends forgot-password emails to active employees', async () => {
    await repo.findActiveEmployeeByEmail('agent@example.test')

    expect(prismaMock.employee.findFirst).toHaveBeenCalledWith({
      where: {
        email: { equals: 'agent@example.test', mode: 'insensitive' },
        isActive: true,
      },
    })
  })

  it('requires unexpired reset tokens for stored-token password reset lookup', async () => {
    vi.useFakeTimers()
    vi.setSystemTime(new Date('2026-06-09T12:00:00.000Z'))

    await repo.findEmployeeByResetToken('reset_123')

    expect(prismaMock.employee.findFirst).toHaveBeenCalledWith({
      where: {
        passwordResetToken: 'reset_123',
        passwordResetExpiresAt: { gt: new Date('2026-06-09T12:00:00.000Z') },
      },
    })
    vi.useRealTimers()
  })

  it('clears stored reset token fields when password changes', async () => {
    await repo.resetPassword('employee_1', 'hash_new')

    expect(prismaMock.employee.update).toHaveBeenCalledWith({
      where: { id: 'employee_1' },
      data: {
        passwordHash: 'hash_new',
        passwordResetToken: null,
        passwordResetExpiresAt: null,
      },
    })
  })
})
