import {
  Controller,
  Get,
  UseGuards,
  Request,
} from '@nestjs/common';
import { PrismaService } from '../../database/prisma.service';
import { JwtAuthGuard } from '../common/guards/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles } from '../common/decorators/roles.decorator';

@Controller('school')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('school')
export class PackageController {
  constructor(private prisma: PrismaService) {}

  @Get('package')
  async getPackageInfo(@Request() req: any) {
    const tenantId = req.user.tenantId;

    const [tenant, teacherCount, studentCount] = await Promise.all([
      this.prisma.tenant.findUnique({
        where: { id: tenantId },
        select: {
          id: true,
          name: true,
          packageType: true,
          teacherQuota: true,
          studentQuota: true,
          storageQuota: true,
          storageUsed: true,
          startDate: true,
          expireDate: true,
          status: true,
        },
      }),
      this.prisma.teacher.count({ where: { tenantId } }),
      this.prisma.student.count({ where: { tenantId } }),
    ]);

    if (!tenant) {
      return null;
    }

    return {
      packageType: tenant.packageType,
      teacherQuota: tenant.teacherQuota,
      studentQuota: tenant.studentQuota,
      storageQuota: Number(tenant.storageQuota),
      teacherCount: teacherCount,
      studentCount: studentCount,
      storageUsed: Number(tenant.storageUsed),
      startDate: tenant.startDate,
      expireDate: tenant.expireDate,
      status: tenant.status,
    };
  }

  @Get('package/usage')
  async getPackageUsage(@Request() req: any) {
    const tenantId = req.user.tenantId;

    const [tenant, teacherCount, studentCount] = await Promise.all([
      this.prisma.tenant.findUnique({
        where: { id: tenantId },
        select: {
          teacherQuota: true,
          studentQuota: true,
          storageQuota: true,
          storageUsed: true,
        },
      }),
      this.prisma.teacher.count({ where: { tenantId } }),
      this.prisma.student.count({ where: { tenantId } }),
    ]);

    if (!tenant) {
      return null;
    }

    return {
      teacher: {
        used: teacherCount,
        quota: tenant.teacherQuota,
        percentage: tenant.teacherQuota > 0 ? Math.round((teacherCount / tenant.teacherQuota) * 100) : 0,
      },
      student: {
        used: studentCount,
        quota: tenant.studentQuota,
        percentage: tenant.studentQuota > 0 ? Math.round((studentCount / tenant.studentQuota) * 100) : 0,
      },
      storage: {
        used: Number(tenant.storageUsed),
        quota: Number(tenant.storageQuota),
        percentage: Number(tenant.storageQuota) > 0 ? Math.round((Number(tenant.storageUsed) / Number(tenant.storageQuota)) * 100) : 0,
      },
    };
  }
}
