import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { Dispute, DisputeEvent } from '@prisma/client';

@Injectable()
export class DisputeService {
  constructor(private prisma: PrismaService) {}

  async createDispute(disputeData: Partial<Dispute>): Promise<Dispute> {
    return this.prisma.dispute.create({
      data: disputeData,
    });
  }

  async getDisputeById(id: number): Promise<Dispute | null> {
    return this.prisma.dispute.findUnique({
      where: { id },
    });
  }

  async updateDisputeStatus(disputeId: number, status: string): Promise<Dispute> {
    return this.prisma.dispute.update({
      where: { id: disputeId },
      data: { status },
    });
  }

  async addEvidence(disputeId: number, evidenceData: any): Promise<DisputeEvent> {
    const event = await this.prisma.disputeEvent.create({
      data: {
        disputeId,
        eventType: 'evidence',
        actorUserId: evidenceData.actorUserId,
        payloadJson: evidenceData.payload,
      },
    });

    // Update dispute status to 'evidence' if not already
    await this.updateDisputeStatus(disputeId, 'evidence');

    return event;
  }

  async resolveDispute(disputeId: number, decisionData: any): Promise<Dispute> {
    return this.prisma.dispute.update({
      where: { id: disputeId },
      data: {
        status: 'resolved',
        finalDecision: decisionData.decision,
        finalReason: decisionData.reason,
        decidedByUserId: decisionData.decidedByUserId,
        decidedAt: new Date(),
      },
    });
  }
}