import { Injectable, NotFoundException } from '@nestjs/common';
import type { Prisma } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { WorkActivityService } from '../work-activity/work-activity.service';
import { CreateVersionPlanDto } from './dto/create-version-plan.dto';
import { UpdateVersionPlanDto } from './dto/update-version-plan.dto';

@Injectable()
export class VersionPlanService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly workActivity: WorkActivityService,
  ) {}

  async create(versionId: string, dto: CreateVersionPlanDto) {
    const version = await this.ensureVersion(versionId);
    const item = await this.prisma.versionPlan.create({
      data: {
        ...this.toPlanData(dto),
        versionId,
        productId: version.productId,
        projectId: version.projectId,
        type: dto.type,
        title: dto.title,
        status: dto.status ?? 'pending',
      },
    });
    const activity = await this.recordPlanActivity(item, 'version_plan_created', 'creation', `新建计划：${item.title}`);
    return { item, activities: [activity] };
  }

  findAll(versionId: string) {
    return this.prisma.versionPlan.findMany({
      where: { versionId },
      orderBy: [{ type: 'asc' }, { createdAt: 'desc' }],
    });
  }

  async update(versionId: string, id: string, dto: UpdateVersionPlanDto) {
    const current = await this.ensurePlanInVersion(versionId, id);
    const data = this.toPlanData(dto);
    if (dto.status === 'in_progress' && !current.actualStartAt) {
      data.actualStartAt = new Date();
    }
    if (dto.status === 'completed' && !current.completedAt) {
      data.completedAt = new Date();
    }
    const item = await this.prisma.versionPlan.update({
      where: { id },
      data,
    });
    const activity = current.status !== item.status ? await this.recordStatusActivity(item, current.status, item.status) : undefined;
    return { item, activities: activity ? [activity] : [] };
  }

  async complete(versionId: string, id: string, dto: UpdateVersionPlanDto) {
    return this.update(versionId, id, {
      ...dto,
      status: 'completed',
      completedAt: dto.completedAt ?? new Date().toISOString(),
    });
  }

  async remove(versionId: string, id: string) {
    await this.ensurePlanInVersion(versionId, id);
    return this.prisma.versionPlan.delete({ where: { id } });
  }

  private toPlanData(dto: Partial<CreateVersionPlanDto>) {
    return {
      ...(dto.type !== undefined && { type: dto.type }),
      ...(dto.title !== undefined && { title: dto.title }),
      ...(dto.status !== undefined && { status: dto.status }),
      ...(dto.owner !== undefined || dto.ownerId !== undefined ? { ownerId: emptyToNull(dto.ownerId ?? dto.owner) } : {}),
      ...(dto.startTime !== undefined || dto.expectedStartAt !== undefined
        ? { expectedStartAt: parseOptionalDate(dto.expectedStartAt ?? dto.startTime) }
        : {}),
      ...(dto.endTime !== undefined || dto.expectedEndAt !== undefined
        ? { expectedEndAt: parseOptionalDate(dto.expectedEndAt ?? dto.endTime) }
        : {}),
      ...(dto.actualStartAt !== undefined && { actualStartAt: parseOptionalDate(dto.actualStartAt) }),
      ...(dto.completedAt !== undefined && { completedAt: parseOptionalDate(dto.completedAt) }),
      ...(dto.resultUrl !== undefined && { resultUrl: emptyToNull(dto.resultUrl) }),
      ...(dto.requirementCoverage !== undefined || dto.linkedRequirementIds !== undefined
        ? { requirementCoverage: toJsonInput(dto.requirementCoverage ?? buildRequirementCoverage(dto.linkedRequirementIds)) }
        : {}),
      ...(dto.logs !== undefined && { logs: toJsonInput(dto.logs) }),
    };
  }

  private async ensureVersion(versionId: string) {
    const version = await this.prisma.version.findUnique({ where: { id: versionId } });
    if (!version) throw new NotFoundException('版本不存在');
    return version;
  }

  private async ensurePlanInVersion(versionId: string, id: string) {
    const plan = await this.prisma.versionPlan.findFirst({ where: { id, versionId } });
    if (!plan) throw new NotFoundException('计划不存在');
    return plan;
  }

  private recordStatusActivity(plan: any, fromStatus: string, toStatus: string) {
    if (toStatus === 'in_progress') {
      return this.recordPlanActivity(plan, 'version_plan_started', 'progress', `开始计划：${plan.title}`, { fromStatus, toStatus });
    }
    if (toStatus === 'completed') {
      return this.recordPlanActivity(plan, 'version_plan_completed', 'delivery', `完成计划：${plan.title}`, { fromStatus, toStatus });
    }
    return undefined;
  }

  private recordPlanActivity(plan: any, action: string, category: string, summary: string, metadata: Record<string, unknown> = {}) {
    return this.workActivity.record({
      versionId: plan.versionId,
      productId: plan.productId,
      projectId: plan.projectId,
      actorId: plan.ownerId,
      sourceType: 'version_plan',
      sourceId: plan.id,
      action,
      category,
      title: plan.title,
      summary,
      metadata,
    });
  }
}

function buildRequirementCoverage(requirementIds: string[] | undefined) {
  return (requirementIds ?? []).map((requirementId) => ({
    requirementId,
    status: 'not_started',
  }));
}

function emptyToNull(value: string | null | undefined): string | null {
  if (value === null) return null;
  if (value === undefined) return null;
  const trimmed = value.trim();
  return trimmed ? trimmed : null;
}

function parseOptionalDate(value: string | null | undefined): Date | null {
  if (!value) return null;
  const date = new Date(value);
  return Number.isFinite(date.getTime()) ? date : null;
}

function toJsonInput(value: unknown): Prisma.InputJsonValue {
  return value as Prisma.InputJsonValue;
}
