import { BadRequestException, Inject, Injectable, NotFoundException } from '@nestjs/common';
import { WorkActivityService } from '../work-activity/work-activity.service';
import { CreateBugDto } from './dto/create-bug.dto';
import { UpdateBugDto } from './dto/update-bug.dto';

export const BUG_PRISMA = 'BUG_PRISMA';

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

  async create(versionId: string, dto: CreateBugDto) {
    const version = await this.ensureVersion(versionId);
    const item = await this.prisma.bug.create({
      data: {
        ...this.toBugData(dto),
        versionId,
        productId: version.productId,
        projectId: version.projectId,
        testCaseVersionId: dto.testCaseVersionId ?? (dto.testCaseId ? versionId : null),
        code: dto.code?.trim() || dto.bugNo?.trim() || createFallbackCode('BUG'),
        title: dto.title,
        status: dto.status ?? 'open',
      },
    });
    const activity = await this.recordBugActivity(item, 'bug_created', 'creation', `新建 Bug：${item.title}`, {
      operator: dto.reporterId ?? dto.reportedBy,
    });
    return { item, activities: [activity] };
  }

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

  async update(versionId: string, id: string, dto: UpdateBugDto) {
    await this.ensureBugInVersion(versionId, id);
    const item = await this.prisma.bug.update({
      where: { id_versionId: { id, versionId } },
      data: this.toBugData(dto),
    });
    await this.workActivity.markXiaobaoSummaryDirty(versionId);
    return { item, activities: [] };
  }

  async updateStatus(
    versionId: string,
    id: string,
    status: string,
    options: { operator?: string; resolution?: string } = {},
  ) {
    const current = await this.ensureBugInVersion(versionId, id);
    const data: Record<string, unknown> = { status };
    if (status === 'fixed' && !current.resolvedAt) data.resolvedAt = new Date();
    if (status === 'closed' && !current.closedAt) data.closedAt = new Date();
    if (options.resolution?.trim()) data.resolution = options.resolution.trim();
    const item = await this.prisma.bug.update({
      where: { id_versionId: { id, versionId } },
      data,
    });
    const activity = await this.recordStatusActivity(item, current.status, status, options.operator);
    return { item, activities: activity ? [activity] : [] };
  }

  async transfer(versionId: string, id: string, assigneeId: string, operator?: string) {
    const current = await this.ensureBugInVersion(versionId, id);
    const item = await this.prisma.bug.update({
      where: { id_versionId: { id, versionId } },
      data: { assigneeId },
    });
    const activity = await this.recordBugActivity(
      item,
      'bug_transferred',
      'progress',
      `转交 Bug：${item.title} → ${assigneeId}`,
      { fromAssigneeId: current.assigneeId, toAssigneeId: assigneeId, operator },
    );
    return { item, activities: [activity] };
  }

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

  private toBugData(dto: Partial<CreateBugDto>) {
    return {
      ...(dto.testCaseId !== undefined && { testCaseId: emptyToNull(dto.testCaseId) }),
      ...(dto.testCaseVersionId !== undefined && { testCaseVersionId: emptyToNull(dto.testCaseVersionId) }),
      ...(dto.code !== undefined || dto.bugNo !== undefined ? { code: dto.code?.trim() || dto.bugNo?.trim() } : {}),
      ...(dto.title !== undefined && { title: dto.title }),
      ...(dto.description !== undefined && { description: dto.description ?? '' }),
      ...(dto.status !== undefined && { status: dto.status }),
      ...(dto.severity !== undefined && { severity: dto.severity ?? 'minor' }),
      ...(dto.priority !== undefined && { priority: parsePriority(dto.priority) ?? 0 }),
      ...(dto.assigneeId !== undefined && { assigneeId: emptyToNull(dto.assigneeId) }),
      ...(dto.reporterId !== undefined || dto.reportedBy !== undefined ? { reporterId: emptyToNull(dto.reporterId ?? dto.reportedBy) } : {}),
      ...(dto.plannedFixAt !== undefined && { plannedFixAt: parseOptionalDate(dto.plannedFixAt) }),
      ...(dto.resolvedAt !== undefined && { resolvedAt: parseOptionalDate(dto.resolvedAt) }),
      ...(dto.closedAt !== undefined && { closedAt: parseOptionalDate(dto.closedAt) }),
      ...(dto.resolution !== undefined && { resolution: emptyToNull(dto.resolution) }),
    };
  }

  private async ensureVersion(versionId: string) {
    const version = await this.prisma.version.findUnique({ where: { id: versionId } });
    if (!version) throw new NotFoundException('版本不存在');
    if (!version.projectId) throw new BadRequestException('Bug 所属版本必须归属于项目');
    return { ...version, projectId: version.projectId };
  }

  private async ensureBugInVersion(versionId: string, id: string) {
    const bug = await this.prisma.bug.findFirst({ where: { id, versionId } });
    if (!bug) throw new NotFoundException('Bug 不存在');
    return bug;
  }

  private recordStatusActivity(bug: any, fromStatus: string, toStatus: string, operator?: string) {
    if (toStatus === 'fixing') {
      return this.recordBugActivity(bug, 'bug_fixing', 'progress', `开始修复 Bug：${bug.title}`, { fromStatus, toStatus, operator });
    }
    if (toStatus === 'fixed') {
      return this.recordBugActivity(bug, 'bug_fixed', 'delivery', `已修复 Bug：${bug.title}`, { fromStatus, toStatus, operator });
    }
    if (toStatus === 'closed') {
      return this.recordBugActivity(bug, 'bug_closed', 'delivery', `已关闭 Bug：${bug.title}`, { fromStatus, toStatus, operator });
    }
    return undefined;
  }

  private recordBugActivity(bug: any, action: string, category: string, summary: string, metadata: Record<string, unknown> = {}) {
    return this.workActivity.record({
      versionId: bug.versionId,
      productId: bug.productId,
      projectId: bug.projectId,
      actorId: metadata.operator as string | undefined ?? bug.assigneeId ?? bug.reporterId,
      sourceType: 'bug',
      sourceId: bug.id,
      action,
      category,
      title: bug.title,
      summary,
      metadata,
    });
  }
}

function createFallbackCode(prefix: string) {
  return `${prefix}-${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;
}
