import type {
  StaffAttendanceRecordViewModel,
  StaffAttendanceRollup,
} from '@/business/staff-attendance/types';

export function countStaffAttendanceStatus(
  records: readonly StaffAttendanceRecordViewModel[],
  status: StaffAttendanceRecordViewModel['status'],
): number {
  return records.filter((record) => record.status === status).length;
}

export function staffAttendanceRate(records: readonly StaffAttendanceRecordViewModel[]): number {
  if (records.length === 0) {
    return 0;
  }

  return Math.round((countStaffAttendanceStatus(records, 'present') / records.length) * 100);
}

export function recentStaffAttendanceRecords(
  records: readonly StaffAttendanceRecordViewModel[],
  limit: number,
): readonly StaffAttendanceRecordViewModel[] {
  return records.slice(0, limit);
}

export function buildStaffAttendanceRollups(
  records: readonly StaffAttendanceRecordViewModel[],
): readonly StaffAttendanceRollup[] {
  const staffNames = Array.from(new Set(records.map((record) => record.userName)));

  return staffNames.map((name) => {
    const staffRecords = records.filter((record) => record.userName === name);
    const absent = countStaffAttendanceStatus(staffRecords, 'absent');

    return {
      name,
      present: countStaffAttendanceStatus(staffRecords, 'present'),
      late: countStaffAttendanceStatus(staffRecords, 'late'),
      absent,
      trend: absent > 2 ? 'down' : 'up',
    };
  });
}
