import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';

interface RequirementQuery {
  productId?: string;
  projectId?: string;
  versionId?: string;
  status?: string;
  priority?: string;
  type?: string;
  q?: string;
  sort?: string;
  cursor?: string;
  limit?: string;
}

interface XiaobaoWarningQuery {
  userId?: string;
  manager?: string;
}

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

  async getVersionDetailData(versionId: string) {
    const version = await this.prisma.version.findUnique({ where: { id: versionId } });
    if (!version) throw new NotFoundException('Version not found');

    const [requirements, versionPlans, devTasks, testCases, bugs] = await Promise.all([
      this.prisma.requirement.findMany({
        where: { versionId },
        orderBy: { createdAt: 'desc' },
      }),
      this.prisma.versionPlan.findMany({
        where: { versionId },
        orderBy: [{ type: 'asc' }, { createdAt: 'desc' }],
      }),
      this.prisma.devTask.findMany({
        where: { versionId },
        orderBy: [{ status: 'asc' }, { updatedAt: 'desc' }],
      }),
      this.prisma.testCase.findMany({
        where: { versionId },
        orderBy: [{ roundNo: 'desc' }, { status: 'asc' }, { updatedAt: 'desc' }],
      }),
      this.prisma.bug.findMany({
        where: { versionId },
        orderBy: [{ status: 'asc' }, { priority: 'asc' }, { updatedAt: 'desc' }],
      }),
    ]);

    return { version, requirements, versionPlans, devTasks, testCases, bugs };
  }

  async listRequirements(query: RequirementQuery) {
    const productId = query.productId?.trim();
    if (!productId) {
      throw new BadRequestException('productId is required for requirement pool queries');
    }

    const limit = parseLimit(query.limit);
    const priority = parsePriority(query.priority);
    const search = query.q?.trim();
    const sortDirection = query.sort === 'created_at_asc' ? 'asc' : 'desc';
    const rows = await this.prisma.requirement.findMany({
      where: {
        productId,
        ...(query.projectId?.trim() ? { projectId: query.projectId.trim() } : {}),
        ...(query.versionId?.trim() ? { versionId: query.versionId.trim() } : {}),
        ...(query.status?.trim() ? { status: query.status.trim() } : {}),
        ...(priority !== undefined ? { priority } : {}),
        ...(query.type?.trim() ? { type: query.type.trim() } : {}),
        ...(search
          ? {
            OR: [
              { code: { contains: search, mode: 'insensitive' as const } },
              { title: { contains: search, mode: 'insensitive' as const } },
            ],
          }
          : {}),
      },
      orderBy: { createdAt: sortDirection },
      take: limit + 1,
      ...(query.cursor
        ? {
          cursor: { id_productId: { id: query.cursor, productId } },
          skip: 1,
        }
        : {}),
    });

    const hasNext = rows.length > limit;
    return {
      items: hasNext ? rows.slice(0, limit) : rows,
      nextCursor: hasNext ? rows[limit]?.id : undefined,
    };
  }

  async getWorkspaceData(userId: string) {
    const normalizedUserId = userId.trim();
    if (!normalizedUserId) throw new BadRequestException('userId is required');

    const [versionPlans, devTasks, testCases, bugs] = await Promise.all([
      this.prisma.versionPlan.findMany({
        where: { ownerId: normalizedUserId, status: { not: 'completed' } },
        orderBy: [{ expectedEndAt: 'asc' }, { updatedAt: 'desc' }],
      }),
      this.prisma.devTask.findMany({
        where: { assigneeId: normalizedUserId, status: { not: 'submitted' } },
        orderBy: [{ priority: 'asc' }, { updatedAt: 'desc' }],
      }),
      this.prisma.testCase.findMany({
        where: { assigneeId: normalizedUserId, status: { notIn: ['passed', 'failed', 'blocked'] } },
        orderBy: [{ priority: 'asc' }, { updatedAt: 'desc' }],
      }),
      this.prisma.bug.findMany({
        where: { assigneeId: normalizedUserId, status: { in: ['open', 'fixing', 'fixed', 'verifying'] } },
        orderBy: [{ priority: 'asc' }, { updatedAt: 'desc' }],
      }),
    ]);

    return { versionPlans, devTasks, testCases, bugs };
  }

  async getXiaobaoWarnings(query: XiaobaoWarningQuery) {
    if (query.manager === 'true') {
      return this.prisma.xiaobaoRiskSummary.findMany({
        where: { riskLevel: { not: 'on_track' } },
        orderBy: [{ riskScore: 'desc' }, { updatedAt: 'desc' }],
      });
    }

    const userId = query.userId?.trim();
    if (!userId) throw new BadRequestException('userId is required');
    const versionIds = await this.getUserOwnedVersionIds(userId);
    if (versionIds.length === 0) return [];

    return this.prisma.xiaobaoRiskSummary.findMany({
      where: {
        versionId: { in: versionIds },
        riskLevel: { not: 'on_track' },
      },
      orderBy: [{ riskScore: 'desc' }, { updatedAt: 'desc' }],
    });
  }

  private async getUserOwnedVersionIds(userId: string): Promise<string[]> {
    const [plans, devTasks, testCases, bugs] = await Promise.all([
      this.prisma.versionPlan.findMany({
        where: { ownerId: userId, status: { not: 'completed' } },
        select: { versionId: true },
      }),
      this.prisma.devTask.findMany({
        where: { assigneeId: userId, status: { not: 'submitted' } },
        select: { versionId: true },
      }),
      this.prisma.testCase.findMany({
        where: { assigneeId: userId, status: { notIn: ['passed', 'failed', 'blocked'] } },
        select: { versionId: true },
      }),
      this.prisma.bug.findMany({
        where: { assigneeId: userId, status: { in: ['open', 'fixing', 'fixed', 'verifying'] } },
        select: { versionId: true },
      }),
    ]);
    return Array.from(new Set([...plans, ...devTasks, ...testCases, ...bugs].map((item) => item.versionId)));
  }
}

function parseLimit(raw?: string): number {
  const parsed = raw ? Number(raw) : 50;
  if (!Number.isFinite(parsed)) return 50;
  return Math.max(1, Math.min(200, Math.floor(parsed)));
}

function parsePriority(raw?: string): number | undefined {
  const normalized = raw?.trim().toUpperCase();
  if (!normalized) return undefined;
  const prefixed = /^P([0-4])$/.exec(normalized);
  if (prefixed) return Number(prefixed[1]);
  const parsed = Number(normalized);
  if (!Number.isFinite(parsed)) return undefined;
  return Math.max(0, Math.min(4, Math.floor(parsed)));
}
