import { StoreModel } from '../../schemas/store.schema.js';
import type { CreateStoreInput, UpdateStoreInput, StoreQueryInput } from '@meshitrack/shared';

export class StoresRepository {
  public async findByHousehold(householdId: string, query: StoreQueryInput) {
    const filter: Record<string, unknown> = { householdId };

    if (query.tags) {
      const tagList = query.tags
        .split(',')
        .map((t) => t.trim())
        .filter(Boolean);
      if (tagList.length > 0) filter['tags'] = { $in: tagList };
    }

    if (query.search) {
      filter['name'] = { $regex: query.search, $options: 'i' };
    }

    if (query.cursor) {
      const id = Buffer.from(query.cursor, 'base64').toString();
      filter['_id'] = { $gt: id };
    }

    const limit = query.limit;
    const items = await StoreModel.find(filter)
      .sort({ _id: 1 })
      .limit(limit + 1)
      .lean()
      .exec();

    const hasMore = items.length > limit;
    const data = hasMore ? items.slice(0, limit) : items;
    const cursor =
      data.length > 0 ? Buffer.from(data[data.length - 1]._id.toString()).toString('base64') : null;

    return { data, pagination: { cursor: hasMore ? cursor : null, hasMore } };
  }

  public async findById(id: string, householdId: string) {
    return StoreModel.findOne({ _id: id, householdId }).lean().exec();
  }

  public async create(data: CreateStoreInput, householdId: string, createdBy: string) {
    const store = new StoreModel({ ...data, householdId, createdBy });
    const saved = await store.save();
    return saved.toObject();
  }

  public async update(id: string, householdId: string, data: UpdateStoreInput) {
    return StoreModel.findOneAndUpdate(
      { _id: id, householdId },
      { $set: data },
      { new: true, lean: true },
    ).exec();
  }

  public async deactivate(id: string, householdId: string) {
    return StoreModel.findOneAndUpdate(
      { _id: id, householdId },
      { $set: { isActive: false } },
      { new: true, lean: true },
    ).exec();
  }
}
