import { Injectable, NotFoundException, ForbiddenException } from '@nestjs/common';
import { PrismaService } from '@core/database/prisma/prisma.service';
import type { AgentArtifact, AgentArtifactType } from '@prisma/client';

export interface CreateArtifactInput {
  organizationId: string;
  sessionId: string;
  turnId?: string;
  createdById: string;
  type: AgentArtifactType;
  title: string;
  data: unknown;
  previewUrl?: string;
  mimeType?: string;
  sizeBytes?: number;
}

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

  async create(input: CreateArtifactInput): Promise<AgentArtifact> {
    return this.prisma.agentArtifact.create({
      data: {
        organizationId: input.organizationId,
        sessionId: input.sessionId,
        turnId: input.turnId ?? null,
        createdById: input.createdById,
        type: input.type,
        title: input.title,
        data: input.data as never,
        previewUrl: input.previewUrl ?? null,
        mimeType: input.mimeType ?? null,
        sizeBytes: input.sizeBytes ?? null,
      },
    });
  }

  async listForSession(sessionId: string, organizationId: string): Promise<AgentArtifact[]> {
    const items = await this.prisma.agentArtifact.findMany({
      where: { sessionId, organizationId },
      orderBy: { createdAt: 'desc' },
      take: 100,
    });
    return items;
  }

  async getById(id: string, organizationId: string): Promise<AgentArtifact> {
    const a = await this.prisma.agentArtifact.findUnique({ where: { id } });
    if (!a) throw new NotFoundException('Artifact not found');
    if (a.organizationId !== organizationId) throw new ForbiddenException();
    return a;
  }
}
