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

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

  async getMessages(groupId: string, page: any = 1, limit: any = 50) {
    const pageNum = Math.max(1, parseInt(page) || 1);
    const limitNum = Math.min(200, parseInt(limit) || 50);
    return this.prisma.message.findMany({
      where: { groupId },
      include: {
        user: { select: { id: true, name: true, profilePicture: true } },
      },
      orderBy: { createdAt: 'desc' },
      skip: (pageNum - 1) * limitNum,
      take: limitNum,
    });
  }

  async create(groupId: string, userId: string, body: string, type = 'TEXT', mediaUrl?: string) {
    return this.prisma.message.create({
      data: { groupId, userId, body, type: type as any, mediaUrl },
      include: {
        user: { select: { id: true, name: true, profilePicture: true } },
      },
    });
  }

  async markRead(messageId: string, userId: string) {
    return this.prisma.messageRead.upsert({
      where: { messageId_userId: { messageId, userId } },
      update: {},
      create: { messageId, userId },
    });
  }

  async pinMessage(id: string, pinned: boolean) {
    return this.prisma.message.update({ where: { id }, data: { pinned } });
  }

  async delete(id: string) {
    return this.prisma.message.delete({ where: { id } });
  }

  async isMember(groupId: string, userId: string) {
    const group = await this.prisma.group.findUnique({ where: { id: groupId } });
    if (group?.type === 'PUBLIC') return true;
    const member = await this.prisma.groupMember.findUnique({
      where: { groupId_userId: { groupId, userId } },
    });
    return !!member;
  }
}
