import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '../../database/prisma.service';
import { StorageService } from '../storage/storage.service';

@Injectable()
export class AdminService {
  private readonly logger = new Logger(AdminService.name);

  constructor(
    private readonly prisma: PrismaService,
    private readonly storageService: StorageService,
  ) {}

  // ── Sistem İstatistikleri ──────────────────────────────────────────

  async getSystemStats() {
    const [
      totalUsers,
      activeUsers,
      totalProjects,
      totalPlans,
      storageStats,
      recentUsers,
      projectsByStatus,
      totalRenderJobs,
      renderJobsByStatus,
    ] = await Promise.all([
      this.prisma.user.count(),
      this.prisma.user.count({ where: { isActive: true } }),
      this.prisma.project.count(),
      this.prisma.plan.count(),
      this.storageService.getStorageStats().catch(() => null),
      this.prisma.user.findMany({
        take: 5,
        orderBy: { createdAt: 'desc' },
        select: { id: true, email: true, firstName: true, lastName: true, createdAt: true },
      }),
      this.prisma.project.groupBy({
        by: ['status'],
        _count: { id: true },
      }),
      this.prisma.renderJob.count(),
      this.prisma.renderJob.groupBy({
        by: ['status'],
        _count: { id: true },
      }),
    ]);

    // Kredi istatistikleri
    const creditStats = await this.prisma.creditTransaction.aggregate({
      _sum: { amount: true },
      where: { type: 'grant' },
    });

    const creditUsed = await this.prisma.creditTransaction.aggregate({
      _sum: { amount: true },
      where: { type: 'usage' },
    });

    return {
      users: {
        total: totalUsers,
        active: activeUsers,
        inactive: totalUsers - activeUsers,
      },
      projects: {
        total: totalProjects,
        byStatus: projectsByStatus.reduce((acc, item) => {
          acc[item.status] = item._count.id;
          return acc;
        }, {} as Record<string, number>),
      },
      renderJobs: {
        total: totalRenderJobs,
        byStatus: renderJobsByStatus.reduce((acc, item) => {
          acc[item.status] = item._count.id;
          return acc;
        }, {} as Record<string, number>),
      },
      credits: {
        totalGranted: creditStats._sum.amount || 0,
        totalUsed: Math.abs(creditUsed._sum.amount || 0),
      },
      plans: {
        total: totalPlans,
      },
      storage: storageStats,
      recentUsers,
    };
  }

  // ── Plan Yönetimi ─────────────────────────────────────────────────

  async getAllPlans() {
    return this.prisma.plan.findMany({
      orderBy: { sortOrder: 'asc' },
      include: {
        _count: {
          select: { subscriptions: true },
        },
      },
    });
  }

  async updatePlan(planId: string, data: {
    displayName?: string;
    description?: string;
    monthlyPrice?: number;
    yearlyPrice?: number;
    monthlyCredits?: number;
    maxDuration?: number;
    maxResolution?: string;
    maxProjects?: number;
    isActive?: boolean;
    features?: any;
  }) {
    return this.prisma.plan.update({
      where: { id: planId },
      data,
    });
  }

  // ── Proje ve Render Yönetimi ──────────────────────────────────────

  async getAllProjects(params: { page: number; limit: number; status?: string; userId?: string }) {
    const { page, limit, status, userId } = params;
    
    // Status filtresini prisma tarafında idari bir kontrole dönüştürmek gerek
    const whereCondition: any = { deletedAt: null };
    if (status) whereCondition.status = status;
    if (userId) whereCondition.userId = userId;

    const [data, total] = await Promise.all([
      this.prisma.project.findMany({
        where: whereCondition,
        include: { user: { select: { email: true, firstName: true, lastName: true } } },
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * limit,
        take: limit,
      }),
      this.prisma.project.count({ where: whereCondition }),
    ]);

    return { data, total, page, limit, totalPages: Math.ceil(total / limit) };
  }

  async getAllRenderJobs(params: { page: number; limit: number; status?: string }) {
    const { page, limit, status } = params;
    
    const whereCondition: any = {};
    if (status) whereCondition.status = status;

    const [data, total] = await Promise.all([
      this.prisma.renderJob.findMany({
        where: whereCondition,
        include: { project: { select: { title: true } } },
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * limit,
        take: limit,
      }),
      this.prisma.renderJob.count({ where: whereCondition }),
    ]);

    return { data, total, page, limit, totalPages: Math.ceil(total / limit) };
  }

  async adminDeleteProject(projectId: string) {
    return this.prisma.project.update({
      where: { id: projectId },
      data: { deletedAt: new Date() },
    });
  }

  // ── Kullanıcı Yönetimi ────────────────────────────────────────────

  async setUserActive(userId: string, isActive: boolean) {
    return this.prisma.user.update({
      where: { id: userId },
      data: { isActive },
    });
  }

  // ── Kullanıcı Kredi Yönetimi ──────────────────────────────────────

  async grantCredits(userId: string, amount: number, description: string) {
    const user = await this.prisma.user.findUnique({
      where: { id: userId },
      include: {
        creditTransactions: {
          orderBy: { createdAt: 'desc' },
          take: 1,
        },
      },
    });

    if (!user) {
      throw new Error('Kullanıcı bulunamadı');
    }

    const currentBalance = user.creditTransactions[0]?.balanceAfter || 0;
    const newBalance = currentBalance + amount;

    return this.prisma.creditTransaction.create({
      data: {
        userId,
        amount,
        type: 'grant',
        description,
        balanceAfter: newBalance,
      },
    });
  }

  // ── Kullanıcı Detay ───────────────────────────────────────────────

  async getUserDetail(userId: string) {
    return this.prisma.user.findUnique({
      where: { id: userId },
      include: {
        roles: {
          include: { role: true },
        },
        projects: {
          take: 10,
          orderBy: { createdAt: 'desc' },
        },
        subscriptions: {
          include: { plan: true },
          take: 1,
          orderBy: { createdAt: 'desc' },
        },
        creditTransactions: {
          take: 10,
          orderBy: { createdAt: 'desc' },
        },
        preferences: true,
      },
    });
  }
}
