import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '@chatapp/database';

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

  async list(userId: string, wsId: string) {
    const reminders = await this.prisma.reminder.findMany({
      where: { userId, workspaceId: wsId },
      orderBy: { remindAt: 'asc' },
    });

    return {
      reminders: reminders.map(r => ({
        id: r.id,
        text: r.text,
        remind_at: r.remindAt,
        status: r.status,
        channel_id: r.channelId,
        created_at: r.createdAt,
        completed_at: r.completedAt,
      })),
    };
  }

  async create(userId: string, wsId: string, dto: { text: string; remind_at: string; channel_id?: string }) {
    const reminder = await this.prisma.reminder.create({
      data: {
        workspaceId: wsId,
        userId,
        text: dto.text,
        remindAt: new Date(dto.remind_at),
        status: 'pending',
        channelId: dto.channel_id || null,
      },
    });
    return {
      id: reminder.id,
      text: reminder.text,
      remind_at: reminder.remindAt,
      status: reminder.status,
      channel_id: reminder.channelId,
    };
  }

  async delete(id: string, userId: string) {
    const reminder = await this.prisma.reminder.findFirst({ where: { id, userId } });
    if (!reminder) throw new NotFoundException('Reminder not found');

    await this.prisma.reminder.delete({ where: { id } });
    return { deleted: true };
  }

  async complete(id: string, userId: string) {
    const reminder = await this.prisma.reminder.findFirst({ where: { id, userId } });
    if (!reminder) throw new NotFoundException('Reminder not found');

    const updated = await this.prisma.reminder.update({
      where: { id },
      data: { status: 'completed', completedAt: new Date() },
    });
    return {
      id: updated.id,
      status: updated.status,
      completed_at: updated.completedAt,
    };
  }
}