import { prisma } from '../../lib/prisma'

export function findEmployeeWithCompanyById(id: string) {
  return prisma.employee.findUnique({
    where: { id },
    include: { company: true },
  })
}

export function findEmployeeById(id: string) {
  return prisma.employee.findUnique({
    where: { id },
  })
}

export function findEmployeeWithCompanyByEmail(email: string) {
  return prisma.employee.findFirst({
    where: {
      email: {
        equals: email,
        mode: 'insensitive',
      },
    },
    include: { company: true },
  })
}

export function findActiveEmployeeByEmail(email: string) {
  return prisma.employee.findFirst({
    where: {
      email: {
        equals: email,
        mode: 'insensitive',
      },
      isActive: true,
    },
  })
}

export function setPasswordResetToken(id: string, passwordResetToken: string, passwordResetExpiresAt: Date) {
  return prisma.employee.update({
    where: { id },
    data: { passwordResetToken, passwordResetExpiresAt },
  })
}

export function updatePreferredLanguage(id: string, preferredLanguage: 'en' | 'fr' | 'ar') {
  return prisma.employee.update({
    where: { id },
    data: { preferredLanguage },
  })
}

export function findEmployeeByResetToken(token: string) {
  return prisma.employee.findFirst({
    where: {
      passwordResetToken: token,
      passwordResetExpiresAt: { gt: new Date() },
    },
  })
}

export function resetPassword(id: string, passwordHash: string) {
  return prisma.employee.update({
    where: { id },
    data: {
      passwordHash,
      passwordResetToken: null,
      passwordResetExpiresAt: null,
    },
  })
}

export function setEmailVerificationToken(id: string, token: string) {
  return prisma.employee.update({
    where: { id },
    data: { emailVerificationToken: token },
  })
}

export function findEmployeeByVerificationToken(token: string) {
  return prisma.employee.findFirst({
    where: { emailVerificationToken: token },
    include: { company: true },
  })
}

export function verifyEmployeeEmail(id: string) {
  return prisma.employee.update({
    where: { id },
    data: {
      emailVerified: new Date(),
      emailVerificationToken: null,
    },
  })
}
