import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Store } from '../../domain/entities/store.entity';
import { IStoreRepository } from '../../domain/repositories/store.repository.interface';

@Injectable()
export class StoreRepository implements IStoreRepository {
  constructor(
    @InjectRepository(Store)
    private readonly repo: Repository<Store>,
  ) {}

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

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

  async save(store: Store): Promise<Store> {
    return this.repo.save(store);
  }

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

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

  async findByIssuerId(
    issuerId: string,
    filters?: { level?: string; parentId?: string; status?: string },
  ): Promise<Store[]> {
    const qb = this.repo.createQueryBuilder('s');
    qb.where('s.issuer_id = :issuerId', { issuerId });

    if (filters?.level) qb.andWhere('s.level = :level', { level: filters.level });
    if (filters?.parentId) qb.andWhere('s.parent_id = :parentId', { parentId: filters.parentId });
    if (filters?.status) qb.andWhere('s.status = :status', { status: filters.status });

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

  async findByIssuerIds(issuerIds: string[]): Promise<Store[]> {
    if (issuerIds.length === 0) return [];
    return this.repo
      .createQueryBuilder('s')
      .where('s.issuer_id IN (:...ids)', { ids: issuerIds })
      .getMany();
  }

  async findTopStores(limit: number): Promise<Store[]> {
    return this.repo
      .createQueryBuilder('s')
      .orderBy('s.created_at', 'DESC')
      .take(limit * 2)
      .getMany();
  }
}
