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

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

  async create(userId: string, title: string, body: string, type = 'INFO', metadata?: object) {
    const id = require('crypto').randomUUID();
    const metaStr = metadata ? JSON.stringify(metadata) : null;
    await this.prisma.$executeRaw`
      INSERT INTO notification (id, userId, title, body, type, metadata)
      VALUES (${id}, ${userId}, ${title}, ${body}, ${type}, ${metaStr})
    `;
    return { id, userId, title, body, type, metadata };
  }

  async findMyNotifications(userId: string) {
    return this.prisma.$queryRaw`
      SELECT * FROM notification WHERE userId = ${userId} ORDER BY createdAt DESC LIMIT 50
    `;
  }

  async getUnreadCount(userId: string) {
    const result: any = await this.prisma.$queryRaw`
      SELECT COUNT(*) as count FROM notification WHERE userId = ${userId} AND isRead = false
    `;
    return Number(result[0]?.count || 0);
  }

  async markAllRead(userId: string) {
    return this.prisma.$executeRaw`
      UPDATE notification SET isRead = true WHERE userId = ${userId} AND isRead = false
    `;
  }

  async markOneRead(id: string) {
    return this.prisma.$executeRaw`
      UPDATE notification SET isRead = true WHERE id = ${id}
    `;
  }
}
