import { Injectable, NotFoundException, Inject } from '@nestjs/common';
import { User } from '../../database/models/user.model';

@Injectable()
export class UsersService {
  constructor(
    @Inject(User)
    private readonly userModel: typeof User,
  ) {}

  async findByEmail(email: string): Promise<User | undefined> {
    return this.userModel.query().findOne({ email });
  }

  async findByEmailWithDepartment(email: string): Promise<User | undefined> {
    return this.userModel.query().findOne({ email }).withGraphFetched('department');
  }

  async findById(id: string): Promise<User | undefined> {
    return this.userModel.query().findById(id).withGraphFetched('department');
  }

  async findAll(): Promise<User[]> {
    return this.userModel.query().withGraphFetched('department').orderBy('created_at', 'desc');
  }

  async updateLastLogin(userId: string): Promise<void> {
    await this.userModel.query().patchAndFetchById(userId, {
      lastLoginAt: new Date().toISOString() as any,
    });
  }

  async updateUserStatus(userId: string, isActive: boolean): Promise<User> {
    const user = await this.userModel.query().patchAndFetchById(userId, {
      isActive,
    });

    if (!user) {
      throw new NotFoundException(`User with ID ${userId} not found`);
    }

    return user;
  }

  async create(data: Partial<User>): Promise<User> {
    return this.userModel.query().insert(data);
  }

  async update(userId: string, data: Partial<User>): Promise<User> {
    const user = await this.userModel.query().patchAndFetchById(userId, data);

    if (!user) {
      throw new NotFoundException(`User with ID ${userId} not found`);
    }

    return user;
  }
}
