import { ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateGoalDto, UpdateGoalDto } from './dto/goal.dto';

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

  findAll(userId: string) {
    return this.prisma.userGoal.findMany({ where: { userId }, orderBy: { createdAt: 'desc' } });
  }

  create(userId: string, dto: CreateGoalDto) {
    return this.prisma.userGoal.create({
      data: {
        userId,
        name: dto.name,
        cost: dto.cost,
        targetDate: dto.targetDate ? new Date(dto.targetDate) : null,
        notes: dto.notes,
      },
    });
  }

  async update(userId: string, id: string, dto: UpdateGoalDto) {
    const goal = await this.prisma.userGoal.findUnique({ where: { id } });
    if (!goal) throw new NotFoundException('الهدف غير موجود.');
    if (goal.userId !== userId) throw new ForbiddenException();

    return this.prisma.userGoal.update({
      where: { id },
      data: {
        name: dto.name,
        cost: dto.cost,
        targetDate: dto.targetDate ? new Date(dto.targetDate) : undefined,
        notes: dto.notes,
        status: dto.status,
      },
    });
  }

  async remove(userId: string, id: string) {
    const goal = await this.prisma.userGoal.findUnique({ where: { id } });
    if (!goal) throw new NotFoundException('الهدف غير موجود.');
    if (goal.userId !== userId) throw new ForbiddenException();

    await this.prisma.userGoal.delete({ where: { id } });
    return { success: true };
  }
}
