import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateLocationDto } from './dto/create-location.dto';
import { UsersService } from '../users/users.service';
import { user_role } from '@prisma/client';

@Injectable()
export class LocationsService {
  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 create(userId: string, createLocationDto: CreateLocationDto) {
    return this.prisma.location.create({
      data: {
        userId,
        ...createLocationDto,
      },
    });
  }

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

    if (user.role === user_role.ADMIN) {
      return this.prisma.location.findMany({
        where: {
          timestamp: { gte: start, lte: end },
        },
        include: { user: { select: { name: true, email: true } } },
        orderBy: { timestamp: 'asc' },
      });
    }

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

    return this.prisma.location.findMany({
      where: {
        userId: { in: allowedUserIds },
        timestamp: { gte: start, lte: end },
      },
      include: { user: { select: { name: true, email: true } } },
      orderBy: { timestamp: 'asc' },
    });
  }

  async findByUser(userId: string, requestingUser: any, date?: string) {
    // Check if the requesting user is allowed to see this user's location
    if (requestingUser.role !== user_role.ADMIN && requestingUser.id !== userId) {
      const subordinateIds = await this.usersService.getSubordinateIds(requestingUser.id);
      if (!subordinateIds.includes(userId)) {
        throw new Error('Unauthorized');
      }
    }

    const { start, end } = this.getDateRange(date);

    return this.prisma.location.findMany({
      where: {
        userId,
        timestamp: { gte: start, lte: end },
      },
      orderBy: { timestamp: 'asc' },
    });
  }
}
