import { Repository } from 'typeorm';
import { AppDataSource } from '../index';
import { Location } from '../entities/Location.entity';

export class LocationRepository {
  private repo: Repository<Location>;

  constructor() {
    this.repo = AppDataSource.getRepository(Location);
  }

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

  findByUserId(userId: string, activeOnly = true): Promise<Location[]> {
    const where: Record<string, unknown> = { userId };
    if (activeOnly) where.isActive = true;
    return this.repo.find({ where, order: { createdAt: 'DESC' } });
  }

  findByUserAndName(userId: string, name: string): Promise<Location | null> {
    return this.repo.findOne({ where: { userId, name, isActive: true } });
  }

  create(data: Partial<Location>): Promise<Location> {
    return this.repo.save(this.repo.create(data));
  }

  async update(id: string, data: Partial<Location>): Promise<Location> {
    await this.repo.update(id, data);
    const location = await this.findById(id);
    if (!location) throw new Error('Location not found');
    return location;
  }

  async softDelete(id: string): Promise<void> {
    await this.repo.update(id, { isActive: false });
  }

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