import { Injectable } from '@nestjs/common';
import { EntityManager, EntityRepository } from '@mikro-orm/postgresql';
import { FilterQuery } from '@mikro-orm/core';
import { Food } from '../entities/food.entity';
import { PaginatedResult } from 'src/common/interfaces/pagination.interface';

type FindFoodsOpts = {
  page?: number;
  limit?: number;
  search?: string;
  orderBy?: string;
  order?: 'asc' | 'desc';
  categoryId?: string;
  isActive?: boolean;
};

@Injectable()
export class FoodRepository extends EntityRepository<Food> {
  constructor(readonly em: EntityManager) {
    super(em, Food);
  }
  /**
   * Find foods with pagination and optional filters.
   * Supports: search (title/content), categoryId, isActive, ordering.
   */
  async findAllPaginated(restId: string, opts: FindFoodsOpts = {}): Promise<PaginatedResult<Food>> {
    const { page = 1, limit = 10, search, orderBy = 'order', order = 'asc', categoryId, isActive } = opts;

    const offset = (page - 1) * limit;

    const where: FilterQuery<Food> = { restaurant: { id: restId } };

    if (typeof isActive === 'boolean') {
      where.isActive = isActive;
    }

    if (search) {
      const pattern = `%${search}%`;
      where.$or = [{ title: { $ilike: pattern } }, { desc: { $ilike: pattern } }];
    }

    if (categoryId) {
      // filter by related category (Food has a single `category` relation)
      Object.assign(where, { category: { id: categoryId } } as unknown as FilterQuery<Food>);
    }

    const [data, total] = await this.findAndCount(where, {
      limit,
      offset,
      orderBy: { [orderBy]: order.toLowerCase() as 'asc' | 'desc' },
      populate: ['category','inventory'],
    });

    const totalPages = Math.ceil(total / limit);

    return {
      data,
      meta: {
        total,
        page,
        limit,
        totalPages,
      },
    };


  }
}
