import { Injectable, BadRequestException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class EmployeesService {
  constructor(private prisma: PrismaService) {}

  async findAll(params?: { departmentId?: number; shiftId?: number; status?: string }) {
    return this.prisma.employee.findMany({
      where: {
        departmentId: params?.departmentId,
        shiftId: params?.shiftId,
        status: params?.status,
      },
      orderBy: [{ lastName: 'asc' }, { firstName: 'asc' }],
      include: {
        department: true,
        shift: true,
      },
    });
  }

  async findById(id: number) {
    const emp = await this.prisma.employee.findUnique({
      where: { id },
      include: {
        department: true,
        shift: true,
        attendances: {
          orderBy: { punchTime: 'desc' },
          take: 50,
        },
      },
    });
    if (!emp) throw new BadRequestException('Employee not found');
    return emp;
  }

  async findByEmpNo(empNo: string) {
    return this.prisma.employee.findUnique({
      where: { empNo },
      include: { department: true, shift: true },
    });
  }

  async create(data: {
    empNo: string;
    firstName: string;
    lastName: string;
    email?: string;
    phone?: string;
    nationalId?: string;
    hireDate?: Date;
    birthDate?: Date;
    address?: string;
    salary?: number;
    departmentId?: number;
    shiftId?: number;
  }) {
    const existing = await this.prisma.employee.findUnique({
      where: { empNo: data.empNo },
    });
    if (existing) {
      throw new BadRequestException(`Employee ${data.empNo} already exists`);
    }
    return this.prisma.employee.create({
      data: {
        empNo: data.empNo,
        firstName: data.firstName,
        lastName: data.lastName,
        email: data.email,
        phone: data.phone,
        nationalId: data.nationalId,
        hireDate: data.hireDate,
        birthDate: data.birthDate,
        address: data.address,
        salary: data.salary ?? 0,
        departmentId: data.departmentId,
        shiftId: data.shiftId,
      },
      include: { department: true, shift: true },
    });
  }

  async update(
    id: number,
    data: {
      empNo?: string;
      firstName?: string;
      lastName?: string;
      email?: string;
      phone?: string;
      nationalId?: string;
      hireDate?: Date;
      birthDate?: Date;
      address?: string;
      salary?: number;
      departmentId?: number;
      shiftId?: number;
      status?: string;
    },
  ) {
    return this.prisma.employee.update({
      where: { id },
      data,
      include: { department: true, shift: true },
    });
  }

  async delete(id: number) {
    return this.prisma.employee.delete({
      where: { id },
    });
  }
}
