import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Favorite } from './favorite.entity';
import { ToggleFavoriteDto } from './dto/favorite.dto';

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

  /** Idempotent toggle - the mobile client only knows "starred" or "not starred". */
  async toggle(dto: ToggleFavoriteDto): Promise<{ favorited: boolean }> {
    const where = {
      anonymousSessionId: dto.anonymousSessionId,
      entityType: dto.entityType,
      entityId: dto.entityId,
    };

    const existing = await this.repo.findOne({ where });
    if (existing) {
      await this.repo.delete(existing.id);
      return { favorited: false };
    }

    await this.repo.save(this.repo.create(where));
    return { favorited: true };
  }

  findBySession(sessionId: string, entityType?: string): Promise<Favorite[]> {
    return this.repo.find({
      where: {
        anonymousSessionId: sessionId,
        ...(entityType ? { entityType } : {}),
      },
      order: { createdAt: 'DESC' },
    });
  }

  async remove(sessionId: string, entityType: string, entityId: number): Promise<boolean> {
    const result = await this.repo.delete({
      anonymousSessionId: sessionId,
      entityType,
      entityId,
    });
    return (result.affected || 0) > 0;
  }
}
