import { Injectable } from '@nestjs/common';
import { PrismaService } from '@modules/shared';
import {
  type IAdminQueryRepository,
  type ModerationQueueResult,
  type DashboardStats,
  type RevenueStatsItem,
  type UserListResult,
  type UserDetail,
  type KycQueueResult,
} from '../../domain/repositories/admin-query.repository';
import { getDashboardStats, getRevenueStats } from './admin-stats.queries';
import { getUsers, getUserDetail } from './admin-user.queries';

@Injectable()
export class PrismaAdminQueryRepository implements IAdminQueryRepository {
  constructor(private readonly prisma: PrismaService) {}

  async getModerationQueue(page: number, limit: number): Promise<ModerationQueueResult> {
    const skip = (page - 1) * limit;

    const [listings, total] = await Promise.all([
      this.prisma.listing.findMany({
        where: { status: 'PENDING_REVIEW' },
        include: {
          property: { select: { title: true, propertyType: true } },
          seller: { select: { fullName: true } },
        },
        orderBy: { createdAt: 'asc' },
        skip,
        take: limit,
      }),
      this.prisma.listing.count({ where: { status: 'PENDING_REVIEW' } }),
    ]);

    return {
      data: listings.map((l) => ({
        listingId: l.id,
        propertyTitle: l.property.title,
        propertyType: l.property.propertyType,
        transactionType: l.transactionType,
        priceVND: l.priceVND,
        sellerName: l.seller.fullName,
        sellerId: l.sellerId,
        moderationScore: l.moderationScore,
        createdAt: l.createdAt,
      })),
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  async getDashboardStats(): Promise<DashboardStats> {
    return getDashboardStats(this.prisma);
  }

  async getRevenueStats(
    startDate: Date,
    endDate: Date,
    groupBy: 'day' | 'month',
  ): Promise<RevenueStatsItem[]> {
    return getRevenueStats(this.prisma, startDate, endDate, groupBy);
  }

  async getUsers(params: {
    page: number;
    limit: number;
    role?: string;
    isActive?: boolean;
    search?: string;
  }): Promise<UserListResult> {
    return getUsers(this.prisma, params);
  }

  async getUserDetail(userId: string): Promise<UserDetail | null> {
    return getUserDetail(this.prisma, userId);
  }

  async getKycQueue(page: number, limit: number): Promise<KycQueueResult> {
    const skip = (page - 1) * limit;

    const [users, total] = await Promise.all([
      this.prisma.user.findMany({
        where: { kycStatus: 'PENDING' },
        select: {
          id: true,
          fullName: true,
          email: true,
          phone: true,
          role: true,
          kycStatus: true,
          kycData: true,
          createdAt: true,
        },
        orderBy: { createdAt: 'asc' },
        skip,
        take: limit,
      }),
      this.prisma.user.count({ where: { kycStatus: 'PENDING' } }),
    ]);

    return {
      data: users.map((u) => ({
        userId: u.id,
        fullName: u.fullName,
        email: u.email,
        phone: u.phone,
        role: u.role,
        kycStatus: u.kycStatus,
        kycData: u.kycData,
        createdAt: u.createdAt,
      })),
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }
}
