import { Injectable } from '@nestjs/common';
import { CreateAttendanceDto } from './dto/create-attendance.dto';
import { UpdateAttendanceDto } from './dto/update-attendance.dto';
import { PrismaService } from '../prisma/prisma.service';
import { UsersService } from '../users/users.service';
import { user_role } from '@prisma/client';

@Injectable()
export class AttendanceService {
  constructor(
    private prisma: PrismaService,
    private usersService: UsersService
  ) { }

  private getDateRange(dateStr?: string) {
    const start = dateStr ? new Date(dateStr) : new Date();
    start.setHours(0, 0, 0, 0);
    const end = new Date(start);
    end.setHours(23, 59, 59, 999);
    return { start, end };
  }

  async checkIn(userId: string, createAttendanceDto: CreateAttendanceDto) {
    // Check if already checked in today? (Optional enhancement)
    return this.prisma.attendance.create({
      data: {
        userId,
        checkInLat: createAttendanceDto.latitude,
        checkInLng: createAttendanceDto.longitude,
        checkInLoc: createAttendanceDto.address,
        checkInTime: new Date(),
      },
    });
  }

  async checkOut(id: string, updateAttendanceDto: UpdateAttendanceDto) {
    return this.prisma.attendance.update({
      where: { id },
      data: {
        checkOutLat: updateAttendanceDto.latitude,
        checkOutLng: updateAttendanceDto.longitude,
        checkOutLoc: updateAttendanceDto.address,
        checkOutTime: new Date(),
      }
    })
  }

  async findAll(user: any, date?: string) {
    const { start, end } = this.getDateRange(date);

    if (user.role === user_role.ADMIN) {
      return this.prisma.attendance.findMany({
        where: {
          checkInTime: { gte: start, lte: end }
        },
        include: { user: true },
        orderBy: { checkInTime: 'desc' }
      });
    }

    const subordinateIds = await this.usersService.getSubordinateIds(user.id);
    const allowedUserIds = [user.id, ...subordinateIds];

    return this.prisma.attendance.findMany({
      where: {
        userId: { in: allowedUserIds },
        checkInTime: { gte: start, lte: end }
      },
      include: { user: true },
      orderBy: { checkInTime: 'desc' }
    });
  }

  findOne(id: string) {
    return this.prisma.attendance.findUnique({ where: { id }, include: { user: true } });
  }

  // Find active check-in for user
  findActiveCheckIn(userId: string) {
    // Logic to find if user has a check-in without check-out today
    // For simplicity, returning the latest one
    return this.prisma.attendance.findFirst({
      where: { userId, checkOutTime: null },
      orderBy: { checkInTime: 'desc' }
    });
  }

  findMyHistory(userId: string) {
    return this.prisma.attendance.findMany({
      where: { userId },
      orderBy: { checkInTime: 'desc' },
      take: 30 // Last 30 records for now
    });
  }
}
