import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { BiometricLogEntry } from './dto/sync-logs.dto';
import * as ExcelJS from 'exceljs';
import { AttendanceMethod } from 'common/enums/attendance-method.enum';
import { Attendance } from 'src/attendance/attendance.entity';

@Injectable()
export class BiometricExcelService {
  constructor(
    @InjectRepository(Attendance)
    private attendanceRepo: Repository<Attendance>,
  ) {}

  async parseExcel(fileBuffer: Buffer): Promise<BiometricLogEntry[]> {
    const workbook = new ExcelJS.Workbook();
    await workbook.xlsx.load(fileBuffer as any);
    const worksheet = workbook.getWorksheet(1);
    if (!worksheet) {
      throw new Error('Worksheet not found');
    }

    const logs: BiometricLogEntry[] = [];

    worksheet.eachRow((row, rowNumber) => {
      if (rowNumber === 1) return;

      const userId = row.getCell(1).toString();
      const timestamp = new Date(row.getCell(2).toString());
      const type = row.getCell(3).toString().toUpperCase();

      if (userId && timestamp && (type === 'IN' || type === 'OUT')) {
        logs.push({ userId, timestamp, type });
      }
    });

    return logs;
  }

  async saveLogs(logs: BiometricLogEntry[]) {
    for (const log of logs) {
      let attendance = await this.attendanceRepo.findOne({
        where: { userId: parseInt(log.userId, 10) },
        order: { createdAt: 'DESC' },
      });

      if (!attendance || log.type === 'IN') {
        attendance = this.attendanceRepo.create({
          userId: parseInt(log.userId, 10),
          checkIn: log.timestamp,
          method: AttendanceMethod.BIOMETRIC,
        });
      } else if (log.type === 'OUT') {
        attendance.checkOut = log.timestamp;
      }

      await this.attendanceRepo.save(attendance);
    }
  }
}
