import { Injectable } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { AuditService } from '../audit/audit.service';
import { resolveEstateScope } from '../common/estate-scope';
import { assertActiveGuardForEstate } from '../common/guard-access';
import { RequestUser } from '../common/request-user';
import { PrismaService } from '../database/prisma.service';
import { CreateIncidentDto } from './dto/create-incident.dto';

@Injectable()
export class IncidentsService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly audit: AuditService
  ) {}

  findAll(user: RequestUser, estateId?: string) {
    const scopedEstateId = resolveEstateScope(user, estateId);
    return this.prisma.incident.findMany({
      where: { estateId: scopedEstateId },
      orderBy: { timestamp: 'desc' },
      take: 100
    });
  }

  async create(dto: CreateIncidentDto, user: RequestUser) {
    const estateId = resolveEstateScope(user, dto.estateId);
    await assertActiveGuardForEstate(this.prisma, dto.guardId, estateId, user);
    const incident = await this.prisma.incident.create({
      data: {
        estateId,
        guardId: dto.guardId,
        type: dto.type,
        description: dto.description,
        metadata: (dto.metadata ?? {}) as Prisma.InputJsonValue
      }
    });

    await this.audit.record({
      estateId,
      actorType: 'GUARD',
      actorId: dto.guardId,
      action: 'INCIDENT_REPORTED',
      metadata: { incidentId: incident.id, type: incident.type, reportedBy: user.id }
    });
    return incident;
  }
}
