import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { APP_DATA_KEYS } from '../data/data-keys';
import { mapAppDataToV22Rows } from '../migration/app-data-v22.mapper';

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;
}

const REQUIREMENT_CREATOR_INCLUDE = {
  creator: { select: { id: true, name: true } },
} as const;

@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 },
        include: REQUIREMENT_CREATOR_INCLUDE,
        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 } },
            ],
          }
          : {}),
      },
      include: REQUIREMENT_CREATOR_INCLUDE,
      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): Promise<WorkspaceRows> {
    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' }],
      }),
    ]);

    const relationResult = { versionPlans, devTasks, testCases, bugs };
    if (hasWorkspaceRows(relationResult)) return relationResult;

    const fallback = await this.getWorkspaceDataFromAppData(normalizedUserId);
    if (hasWorkspaceRows(fallback)) return fallback;

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

  private async getWorkspaceDataFromAppData(userId: string): Promise<WorkspaceRows> {
    const rows = await this.prisma.appData.findMany({
      where: { key: { in: [...APP_DATA_KEYS] } },
      select: { key: true, value: true },
    });
    const snapshot = Object.fromEntries(rows.map((row) => [row.key, row.value]));
    const mapped = mapAppDataToV22Rows(snapshot);

    return {
      versionPlans: mapped.versionPlans
        .filter((plan) => plan.ownerId === userId && plan.status !== 'completed')
        .sort(comparePlanRows),
      devTasks: mapped.devTasks
        .filter((task) => task.assigneeId === userId && task.status !== 'submitted')
        .sort(comparePriorityThenUpdatedRows),
      testCases: mapped.testCases
        .filter((testCase) => testCase.assigneeId === userId && !['passed', 'failed', 'blocked'].includes(testCase.status))
        .sort(comparePriorityThenUpdatedRows),
      bugs: mapped.bugs
        .filter((bug) => bug.assigneeId === userId && ['open', 'fixing', 'fixed', 'verifying'].includes(bug.status))
        .sort(comparePriorityThenUpdatedRows),
    };
  }

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

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

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

  private async attachLatestXiaobaoInsights(rows: any[]) {
    const versionIds = Array.from(new Set(rows.map((row) => readString(row?.versionId)).filter(isText)));
    if (versionIds.length === 0) return rows;

    const insights = await this.prisma.xiaobaoRiskInsight.findMany({
      where: {
        versionId: { in: versionIds },
        status: 'generated',
      },
      orderBy: [{ createdAt: 'desc' }],
    });
    const latestByVersion = new Map<string, any>();
    for (const insight of insights) {
      const versionId = readString(insight?.versionId);
      if (versionId && !latestByVersion.has(versionId)) {
        latestByVersion.set(versionId, insight);
      }
    }

    return rows.map((row) => {
      const latest = latestByVersion.get(String(row.versionId));
      const latestInsight = latest ? normalizeXiaobaoInsight(latest) : undefined;
      return latestInsight ? { ...row, latestInsight } : row;
    });
  }

  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)));
  }
}

type WorkspaceRows = {
  versionPlans: unknown[];
  devTasks: unknown[];
  testCases: unknown[];
  bugs: unknown[];
};

type PriorityUpdatedRow = {
  priority?: number;
  updatedAt?: string;
};

type PlanSortRow = {
  expectedEndAt?: string;
  updatedAt?: string;
};

function hasWorkspaceRows(rows: WorkspaceRows): boolean {
  return rows.versionPlans.length > 0
    || rows.devTasks.length > 0
    || rows.testCases.length > 0
    || rows.bugs.length > 0;
}

function comparePlanRows(a: PlanSortRow, b: PlanSortRow): number {
  const endDiff = dateSortValue(a.expectedEndAt, Number.POSITIVE_INFINITY)
    - dateSortValue(b.expectedEndAt, Number.POSITIVE_INFINITY);
  if (endDiff !== 0) return endDiff;
  return dateSortValue(b.updatedAt, 0) - dateSortValue(a.updatedAt, 0);
}

function comparePriorityThenUpdatedRows(a: PriorityUpdatedRow, b: PriorityUpdatedRow): number {
  const priorityDiff = (a.priority ?? 0) - (b.priority ?? 0);
  if (priorityDiff !== 0) return priorityDiff;
  return dateSortValue(b.updatedAt, 0) - dateSortValue(a.updatedAt, 0);
}

function dateSortValue(value: string | undefined, fallback: number): number {
  if (!value) return fallback;
  const time = new Date(value).getTime();
  return Number.isFinite(time) ? time : fallback;
}

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)));
}

function normalizeXiaobaoInsight(row: any) {
  const payload = readRecord(row?.insight);
  const nestedInsight = readRecord(payload.insight);
  const insight = Object.keys(nestedInsight).length > 0 ? nestedInsight : payload;
  const versionId = readString(payload.versionId) ?? readString(row?.versionId);
  const riskSignature = readString(payload.riskSignature) ?? readString(row?.riskSignature);
  if (!versionId || !riskSignature || Object.keys(insight).length === 0) return undefined;

  return {
    versionId,
    riskSignature,
    insight,
    generatedAt: readString(payload.generatedAt) ?? toIso(row?.createdAt) ?? new Date(0).toISOString(),
    providerInfo: readProviderInfo(payload.providerInfo),
  };
}

function readProviderInfo(value: unknown): { providerId?: string; model?: string } | undefined {
  const row = readRecord(value);
  const providerId = readString(row.providerId);
  const model = readString(row.model);
  if (!providerId && !model) return undefined;
  return {
    ...(providerId ? { providerId } : {}),
    ...(model ? { model } : {}),
  };
}

function readRecord(value: unknown): Record<string, any> {
  return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, any> : {};
}

function readString(value: unknown): string | undefined {
  return typeof value === 'string' && value.trim() ? value.trim() : undefined;
}

function isText(value: string | undefined): value is string {
  return Boolean(value);
}

function toIso(value: unknown): string | undefined {
  if (value instanceof Date) return value.toISOString();
  if (typeof value === 'string') {
    const time = new Date(value).getTime();
    if (Number.isFinite(time)) return new Date(time).toISOString();
  }
  return undefined;
}
