import { Inject, Injectable, Optional } from '@nestjs/common';
import { XiaobaoRiskService } from '../xiaobao/xiaobao-risk.service';

export interface WorkActivityRecordInput {
  versionId?: string | null;
  productId?: string | null;
  projectId?: string | null;
  actorId?: string | null;
  actorName?: string | null;
  sourceType: string;
  sourceId: string;
  sourceVersionId?: string | null;
  action: string;
  title: string;
  category?: string;
  summary?: string;
  metadata?: Record<string, unknown>;
  occurredAt?: string | Date | null;
}

export const WORK_ACTIVITY_PRISMA = 'WORK_ACTIVITY_PRISMA';

@Injectable()
export class WorkActivityService {
  constructor(
    @Inject(WORK_ACTIVITY_PRISMA) private readonly prisma: any,
    @Optional() private readonly xiaobaoRisk?: XiaobaoRiskService,
  ) {}

  findAll() {
    return this.prisma.workActivity.findMany({ orderBy: { occurredAt: 'desc' } });
  }

  async record(input: WorkActivityRecordInput) {
    const versionId = input.versionId ?? input.sourceVersionId ?? null;
    const metadata = {
      ...(input.metadata ?? {}),
      ...(input.category ? { category: input.category } : {}),
      ...(input.summary ? { summary: input.summary } : {}),
    };

    const activity = await this.prisma.workActivity.create({
      data: {
        versionId,
        productId: input.productId ?? null,
        projectId: input.projectId ?? null,
        actorId: input.actorId ?? null,
        actorName: input.actorName ?? '',
        sourceType: input.sourceType,
        sourceId: input.sourceId,
        sourceVersionId: input.sourceVersionId ?? versionId,
        action: input.action,
        title: input.title,
        metadata,
        occurredAt: parseDate(input.occurredAt) ?? new Date(),
      },
    });

    if (versionId) {
      await this.markXiaobaoSummaryDirty(versionId);
    }

    return activity;
  }

  async remove(id: string) {
    await this.prisma.workActivity.deleteMany({ where: { id } });
    return { deleted: true };
  }

  async markXiaobaoSummaryDirty(versionId: string) {
    if (this.xiaobaoRisk) {
      await this.xiaobaoRisk.markDirtyAndEnqueue(versionId);
      return;
    }

    const riskSignature = `dirty:${versionId}`;
    await this.prisma.xiaobaoRiskSummary.upsert({
      where: { versionId },
      update: { dirty: true },
      create: {
        versionId,
        riskLevel: 'attention',
        riskScore: 1,
        confidence: 0,
        riskSignature,
        summary: {
          versionId,
          riskLevel: 'attention',
          riskScore: 1,
          confidence: 0,
          riskSignature,
          dirty: true,
        },
        dirty: true,
      },
    });
  }
}

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