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

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

@Injectable()
export class RestRepository extends EntityRepository<Restaurant> {
  constructor(readonly em: EntityManager) {
    super(em, Restaurant);
  }

  /**
   * Find restaurants with pagination and optional filters.
   * Supports: search (name/slug/domain/address), isActive, plan, ordering.
   */
  async findAllPaginated(opts: FindRestaurantsOpts = {}): Promise<PaginatedResult<Restaurant>> {
    const {
      page = 1,
      limit = 10,
      search,
      isActive,
      plan,
      orderBy = 'createdAt',
      order = 'desc',
    } = opts;

    const offset = (page - 1) * limit;

    const where: FilterQuery<Restaurant> = {};

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

    if (plan) {
      where.plan = plan;
    }

    if (search) {
      const pattern = `%${search}%`;
      where.$or = [
        { name: { $ilike: pattern } },
        { slug: { $ilike: pattern } },
        { domain: { $ilike: pattern } },
        { address: { $ilike: pattern } },
      ];
    }

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

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

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