import type { PrismaClient, PromptRequest } from '@prisma/client';

export interface IPromptRequestRepository {
  findAll(projectId?: string): Promise<PromptRequest[]>;
  findGlobal(): Promise<PromptRequest[]>;
  findById(id: string): Promise<PromptRequest | null>;
  findByNameAndProject(name: string, projectId: string | null): Promise<PromptRequest | null>;
  findBySession(sessionId: string, projectId?: string): Promise<PromptRequest[]>;
  create(data: { name: string; content: string; projectId?: string; priority?: number; createdBySession?: string; createdByUserId?: string }): Promise<PromptRequest>;
  update(id: string, data: { content?: string; priority?: number }): Promise<PromptRequest>;
  delete(id: string): Promise<void>;
}

export class PromptRequestRepository implements IPromptRequestRepository {
  constructor(private readonly prisma: PrismaClient) {}

  async findAll(projectId?: string): Promise<PromptRequest[]> {
    const include = { project: { select: { name: true } } };
    if (projectId !== undefined) {
      return this.prisma.promptRequest.findMany({
        where: { OR: [{ projectId }, { projectId: null }] },
        include,
        orderBy: { createdAt: 'desc' },
      });
    }
    return this.prisma.promptRequest.findMany({ include, orderBy: { createdAt: 'desc' } });
  }

  async findGlobal(): Promise<PromptRequest[]> {
    return this.prisma.promptRequest.findMany({
      where: { projectId: null },
      include: { project: { select: { name: true } } },
      orderBy: { createdAt: 'desc' },
    });
  }

  async findById(id: string): Promise<PromptRequest | null> {
    return this.prisma.promptRequest.findUnique({ where: { id } });
  }

  async findByNameAndProject(name: string, projectId: string | null): Promise<PromptRequest | null> {
    return this.prisma.promptRequest.findUnique({
      where: { name_projectId: { name, projectId: projectId ?? '' } },
    });
  }

  async findBySession(sessionId: string, projectId?: string): Promise<PromptRequest[]> {
    const where: Record<string, unknown> = { createdBySession: sessionId };
    if (projectId !== undefined) {
      where['OR'] = [{ projectId }, { projectId: null }];
    }
    return this.prisma.promptRequest.findMany({
      where,
      orderBy: { createdAt: 'desc' },
    });
  }

  async create(data: { name: string; content: string; projectId?: string; priority?: number; createdBySession?: string; createdByUserId?: string }): Promise<PromptRequest> {
    return this.prisma.promptRequest.create({ data });
  }

  async update(id: string, data: { content?: string; priority?: number }): Promise<PromptRequest> {
    return this.prisma.promptRequest.update({ where: { id }, data });
  }

  async delete(id: string): Promise<void> {
    await this.prisma.promptRequest.delete({ where: { id } });
  }
}
