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

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

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

  /**
   * Find coupons with pagination and optional filters.
   * Supports: search (code/name), type, isActive, ordering.
   */
  async findAllPaginated(restId: string, opts: FindCouponsOpts = {}): Promise<PaginatedResult<Coupon>> {
    const { page = 1, limit = 10, search, orderBy = 'createdAt', order = 'desc', type, isActive } = opts;

    const offset = (page - 1) * limit;

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

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

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

    if (search) {
      const pattern = `%${search}%`;
      where.$or = [{ code: { $ilike: pattern } }, { name: { $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,
      },
    };
  }
}
