import { BadRequestException, Inject, Injectable, NotFoundException } from '@nestjs/common';
import { WorkActivityService } from '../work-activity/work-activity.service';
import { CreateDevTaskDto } from './dto/create-dev-task.dto';
import { UpdateDevTaskDto } from './dto/update-dev-task.dto';

export const DEV_TASK_PRISMA = 'DEV_TASK_PRISMA';

@Injectable()
export class DevTaskService {
  constructor(
    @Inject(DEV_TASK_PRISMA) private readonly prisma: any,
    private readonly workActivity: WorkActivityService,
  ) {}

  async create(versionId: string, dto: CreateDevTaskDto) {
    const version = await this.ensureVersion(versionId);
    if (!version.projectId) {
      throw new BadRequestException('开发任务所属版本必须归属于项目');
    }
    const item = await this.prisma.devTask.create({
      data: {
        ...this.toTaskData(dto),
        versionId,
        productId: version.productId,
        projectId: version.projectId,
        code: dto.code?.trim() || dto.taskNo?.trim() || createFallbackDevCode(),
        title: dto.title,
        status: dto.status ?? 'todo',
        isBlocked: dto.isBlocked ?? false,
      },
    });
    const activity = await this.recordTaskActivity(item, 'dev_task_created', 'creation', `新建开发任务：${item.title}`);
    return { item, activities: [activity] };
  }

  findAll(versionId: string) {
    return this.prisma.devTask.findMany({
      where: { versionId },
      orderBy: [{ status: 'asc' }, { updatedAt: 'desc' }],
    });
  }

  async update(versionId: string, id: string, dto: UpdateDevTaskDto) {
    await this.ensureTaskInVersion(versionId, id);
    const item = await this.prisma.devTask.update({
      where: { id_versionId: { id, versionId } },
      data: this.toTaskData(dto),
    });
    await this.workActivity.markXiaobaoSummaryDirty(versionId);
    return { item, activities: [] };
  }

  async updateStatus(versionId: string, id: string, status: string) {
    const current = await this.ensureTaskInVersion(versionId, id);
    const data: Record<string, unknown> = { status };
    if (status === 'in_progress' && !current.startDate) data.startDate = new Date();
    if (status === 'submitted' && !current.completedAt) data.completedAt = new Date();
    const item = await this.prisma.devTask.update({
      where: { id_versionId: { id, versionId } },
      data,
    });
    const activity = await this.recordStatusActivity(item, current.status, status);
    return { item, activities: activity ? [activity] : [] };
  }

  async setBlocked(versionId: string, id: string, blocked: boolean, reason?: string) {
    await this.ensureTaskInVersion(versionId, id);
    const item = await this.prisma.devTask.update({
      where: { id_versionId: { id, versionId } },
      data: {
        isBlocked: blocked,
        blockReason: blocked ? reason : null,
      },
    });
    const activity = await this.recordTaskActivity(
      item,
      blocked ? 'dev_task_blocked' : 'dev_task_unblocked',
      blocked ? 'risk' : 'progress',
      blocked ? `标记阻塞：${reason?.trim() || item.title}` : `解除阻塞：${item.title}`,
      { blocker: blocked ? reason : undefined },
    );
    return { item, activities: [activity] };
  }

  async transfer(versionId: string, id: string, assigneeId: string) {
    const current = await this.ensureTaskInVersion(versionId, id);
    const item = await this.prisma.devTask.update({
      where: { id_versionId: { id, versionId } },
      data: { assigneeId },
    });
    const activity = await this.recordTaskActivity(
      item,
      'dev_task_transferred',
      'progress',
      `转派开发任务：${item.title}`,
      { fromAssigneeId: current.assigneeId, toAssigneeId: assigneeId },
    );
    return { item, activities: [activity] };
  }

  async remove(versionId: string, id: string) {
    await this.ensureTaskInVersion(versionId, id);
    const item = await this.prisma.devTask.delete({ where: { id_versionId: { id, versionId } } });
    await this.workActivity.markXiaobaoSummaryDirty(versionId);
    return item;
  }

  private toTaskData(dto: Partial<CreateDevTaskDto>) {
    return {
      ...(dto.requirementId !== undefined && { requirementId: emptyToNull(dto.requirementId) }),
      ...(dto.requirementProductId !== undefined && { requirementProductId: emptyToNull(dto.requirementProductId) }),
      ...(dto.categoryId !== undefined && { categoryId: emptyToNull(dto.categoryId) }),
      ...(dto.code !== undefined || dto.taskNo !== undefined ? { code: dto.code?.trim() || dto.taskNo?.trim() } : {}),
      ...(dto.title !== undefined && { title: dto.title }),
      ...(dto.description !== undefined && { description: dto.description ?? '' }),
      ...(dto.status !== undefined && { status: dto.status }),
      ...(dto.priority !== undefined && { priority: parsePriority(dto.priority) ?? 0 }),
      ...(dto.assigneeId !== undefined && { assigneeId: emptyToNull(dto.assigneeId) }),
      ...(dto.creatorId !== undefined || dto.createdBy !== undefined ? { creatorId: emptyToNull(dto.creatorId ?? dto.createdBy) } : {}),
      ...(dto.isBlocked !== undefined && { isBlocked: dto.isBlocked }),
      ...(dto.blockReason !== undefined && { blockReason: emptyToNull(dto.blockReason) }),
      ...(dto.expectedStartAt !== undefined && { expectedStartAt: parseOptionalDate(dto.expectedStartAt) }),
      ...(dto.expectedEndAt !== undefined && { expectedEndAt: parseOptionalDate(dto.expectedEndAt) }),
      ...(dto.actualStartAt !== undefined || dto.startDate !== undefined
        ? { startDate: parseOptionalDate(dto.actualStartAt ?? dto.startDate) }
        : {}),
      ...(dto.actualEndAt !== undefined || dto.completedAt !== undefined
        ? { completedAt: parseOptionalDate(dto.actualEndAt ?? dto.completedAt) }
        : {}),
      ...(dto.estimateHours !== undefined && { estimateHours: dto.estimateHours }),
      ...(dto.aiEstimateHours !== undefined && { aiEstimateHours: dto.aiEstimateHours }),
      ...(dto.references !== undefined && { references: toJsonInput(dto.references) }),
      ...(dto.aiDraft !== undefined && { aiDraft: dto.aiDraft }),
      ...(dto.aiDraftAt !== undefined && { aiDraftAt: parseOptionalDate(dto.aiDraftAt) }),
    };
  }

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

  private async ensureTaskInVersion(versionId: string, id: string) {
    const task = await this.prisma.devTask.findFirst({ where: { id, versionId } });
    if (!task) throw new NotFoundException('开发任务不存在');
    return task;
  }

  private recordStatusActivity(task: any, fromStatus: string, toStatus: string) {
    if (toStatus === 'in_progress') {
      return this.recordTaskActivity(task, 'dev_task_started', 'progress', `开始开发：${task.title}`, { fromStatus, toStatus });
    }
    if (toStatus === 'testing') {
      return this.recordTaskActivity(task, 'dev_task_self_testing', 'progress', `进入自测：${task.title}`, { fromStatus, toStatus });
    }
    if (toStatus === 'submitted') {
      return this.recordTaskActivity(task, 'dev_task_submitted', 'delivery', `已提测开发任务：${task.title}`, { fromStatus, toStatus });
    }
    return undefined;
  }

  private recordTaskActivity(task: any, action: string, category: string, summary: string, metadata: Record<string, unknown> = {}) {
    return this.workActivity.record({
      versionId: task.versionId,
      productId: task.productId,
      projectId: task.projectId,
      actorId: task.assigneeId ?? task.creatorId,
      sourceType: 'dev_task',
      sourceId: task.id,
      action,
      category,
      title: task.title,
      summary,
      metadata,
    });
  }
}

function createFallbackDevCode() {
  return `DEV-${Date.now().toString(36).toUpperCase()}`;
}

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 parsePriority(value: string | number | null | undefined): number | undefined {
  if (value === null || value === undefined || value === '') return undefined;
  if (typeof value === 'number') return Number.isFinite(value) ? Math.max(0, Math.min(4, Math.floor(value))) : undefined;
  const match = /^P([0-4])$/i.exec(value.trim());
  if (match) return Number(match[1]);
  const parsed = Number(value);
  return Number.isFinite(parsed) ? Math.max(0, Math.min(4, Math.floor(parsed))) : undefined;
}

function toJsonInput(value: unknown): any {
  return value as any;
}
