import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../database/prisma.service';
import { MissionStatus } from '@prisma/client';

@Injectable()
export class AdminService {
  constructor(private readonly prisma: PrismaService) {}

  async getStats() {
    const [families, children, missions, assignments] = await Promise.all([
      this.prisma.family.count(),
      this.prisma.child.count(),
      this.prisma.mission.count({ where: { status: MissionStatus.PUBLISHED } }),
      this.prisma.missionAssignment.count({ where: { status: 'COMPLETED' } }),
    ]);
    return { families, children, publishedMissions: missions, completedAssignments: assignments };
  }

  async listFamilies(page = 1, limit = 20) {
    const skip = (page - 1) * limit;
    const [items, total] = await Promise.all([
      this.prisma.family.findMany({
        skip,
        take: limit,
        include: { members: { include: { user: true } } },
        orderBy: { createdAt: 'desc' },
      }),
      this.prisma.family.count(),
    ]);
    return { items, total, page, limit };
  }

  async listMissions(page = 1, limit = 20) {
    const skip = (page - 1) * limit;
    const [items, total] = await Promise.all([
      this.prisma.mission.findMany({
        skip, take: limit,
        include: { subject: true },
        orderBy: { createdAt: 'desc' },
      }),
      this.prisma.mission.count(),
    ]);
    return { items, total, page, limit };
  }

  async createSubject(data: { name: string; nameEn?: string; slug: string; emoji?: string; color?: string }) {
    return this.prisma.subject.create({ data });
  }

  async createSkill(data: { subjectId: string; name: string; slug: string; parentId?: string; description?: string }) {
    return this.prisma.skill.create({ data });
  }

  async createMission(data: any) {
    return this.prisma.mission.create({ data, include: { subject: true } });
  }

  async updateMissionStatus(id: string, status: MissionStatus) {
    return this.prisma.mission.update({ where: { id }, data: { status } });
  }

  async getAuditLogs(page = 1, limit = 50) {
    const skip = (page - 1) * limit;
    const [items, total] = await Promise.all([
      this.prisma.auditLog.findMany({
        skip, take: limit,
        include: { user: { select: { id: true, name: true, email: true } } },
        orderBy: { createdAt: 'desc' },
      }),
      this.prisma.auditLog.count(),
    ]);
    return { items, total, page, limit };
  }

  async listSubjects() {
    return this.prisma.subject.findMany({
      include: { skills: true },
      orderBy: { sortOrder: 'asc' },
    });
  }

  async listSkills(subjectId?: string) {
    return this.prisma.skill.findMany({
      where: subjectId ? { subjectId } : undefined,
      include: { subject: true, parent: true },
      orderBy: { name: 'asc' },
    });
  }
}
