import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../infrastructure/database/prisma.service';

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

  async create(data: {
    userId?: string;
    email?: string;
    type?: string;
    content?: string;
    contact?: string;
  }) {
    return this.prisma.feedback.create({
      data: {
        userId: data.userId ?? null,
        email: data.email ?? data.contact ?? null,
        category: data.type ?? 'general',
        content: data.content ?? '',
      },
    });
  }

  async findAll() {
    return this.prisma.feedback.findMany({ orderBy: { createdAt: 'desc' } });
  }

  async findByUserId(userId: string) {
    return this.prisma.feedback.findMany({
      where: { userId },
      orderBy: { createdAt: 'desc' },
    });
  }

  async updateStatus(id: string, status: string) {
    return this.prisma.feedback.update({
      where: { id },
      data: { status },
    });
  }

  async getStats() {
    const byCategory = await this.prisma.feedback.groupBy({
      by: ['category'],
      _count: true,
    });
    const byStatus = await this.prisma.feedback.groupBy({
      by: ['status'],
      _count: true,
    });
    const total = await this.prisma.feedback.count();

    const byType: Record<string, number> = {};
    for (const g of byCategory) {
      byType[g.category] = g._count;
    }
    const byStatusObj: Record<string, number> = {};
    for (const g of byStatus) {
      byStatusObj[g.status] = g._count;
    }
    return { total, byType, byStatus: byStatusObj };
  }
}
