import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Employee } from '../../domain/entities/employee.entity';
import { IEmployeeRepository } from '../../domain/repositories/employee.repository.interface';

@Injectable()
export class EmployeeRepository implements IEmployeeRepository {
  constructor(
    @InjectRepository(Employee)
    private readonly repo: Repository<Employee>,
  ) {}

  async findById(id: string): Promise<Employee | null> {
    return this.repo.findOne({ where: { id } });
  }

  async create(data: Partial<Employee>): Promise<Employee> {
    const entity = this.repo.create(data);
    return this.repo.save(entity);
  }

  async save(employee: Employee): Promise<Employee> {
    return this.repo.save(employee);
  }

  async delete(id: string): Promise<void> {
    await this.repo.delete(id);
  }

  async findByIssuerId(
    issuerId: string,
    filters?: { storeId?: string; role?: string },
  ): Promise<Employee[]> {
    const qb = this.repo.createQueryBuilder('e');
    qb.where('e.issuer_id = :issuerId', { issuerId });

    if (filters?.storeId) qb.andWhere('e.store_id = :storeId', { storeId: filters.storeId });
    if (filters?.role) qb.andWhere('e.role = :role', { role: filters.role });

    qb.orderBy('e.created_at', 'DESC');
    return qb.getMany();
  }

  async count(where?: Partial<Record<string, any>>): Promise<number> {
    return this.repo.count({ where: where as any });
  }
}
