import type { StoresRepository } from './stores.repository.js';
import type { CreateStoreInput, UpdateStoreInput, StoreQueryInput } from '@meshitrack/shared';
import { NotFoundError } from '../../common/errors.js';

interface Deps {
  storesRepository: StoresRepository;
}

export class StoresService {
  private readonly storesRepository: StoresRepository;

  public constructor({ storesRepository }: Deps) {
    this.storesRepository = storesRepository;
  }

  public async list(householdId: string, query: StoreQueryInput) {
    return this.storesRepository.findByHousehold(householdId, query);
  }

  public async getById(id: string, householdId: string) {
    const store = await this.storesRepository.findById(id, householdId);
    if (!store) throw new NotFoundError('Store not found');
    return store;
  }

  public async create(data: CreateStoreInput, householdId: string, userId: string) {
    return this.storesRepository.create(data, householdId, userId);
  }

  public async update(id: string, householdId: string, data: UpdateStoreInput) {
    await this.getById(id, householdId);
    const updated = await this.storesRepository.update(id, householdId, data);
    if (!updated) throw new NotFoundError('Store not found');
    return updated;
  }

  public async deactivate(id: string, householdId: string) {
    await this.getById(id, householdId);
    const updated = await this.storesRepository.deactivate(id, householdId);
    if (!updated) throw new NotFoundError('Store not found');
    return updated;
  }
}
