import {
  Injectable,
  NotFoundException,
  ConflictException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Favorite } from './entities/favorite.entity';
import { CreateFavoriteDto } from './dto/create-favorite.dto';
import { PaginationOptions } from '../common/interfaces';

@Injectable()
export class FavoritesService {
  constructor(
    @InjectRepository(Favorite)
    private readonly favoriteRepository: Repository<Favorite>,
  ) {}

  async create(userId: string, createFavoriteDto: CreateFavoriteDto): Promise<Favorite> {
    const existing = await this.favoriteRepository.findOne({
      where: {
        userId,
        contentId: createFavoriteDto.contentId,
        contentType: createFavoriteDto.contentType,
      },
    });

    if (existing) {
      throw new ConflictException('This item is already in your favorites');
    }

    const favorite = this.favoriteRepository.create({
      userId,
      ...createFavoriteDto,
    });

    return this.favoriteRepository.save(favorite);
  }

  async findAllByUser(userId: string, pagination: PaginationOptions) {
    const { page, limit } = pagination;
    const skip = (page - 1) * limit;

    const [favorites, total] = await this.favoriteRepository.findAndCount({
      where: { userId },
      order: { createdAt: 'DESC' },
      skip,
      take: limit,
    });

    return {
      data: favorites,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  async remove(id: string, userId: string): Promise<void> {
    const favorite = await this.favoriteRepository.findOne({
      where: { id, userId },
    });

    if (!favorite) {
      throw new NotFoundException(`Favorite with ID "${id}" not found`);
    }

    await this.favoriteRepository.remove(favorite);
  }
}
