import { Injectable } from '@nestjs/common';
import { PrismaService } from '@/database/services/prisma.service';
import { Photo } from '../domain/Photo';
import { PhotoMapper } from '../mappers/photo.mapper';
import { ShootingMapper } from '../mappers/shooting.mapper';

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

  async addFavorite(customerId: string, photoId: string): Promise<void> {
    await this.prisma.customerFavorite.create({
      data: {
        customerId,
        photoId,
      },
    });
  }

  async removeFavorite(customerId: string, photoId: string): Promise<void> {
    await this.prisma.customerFavorite.delete({
      where: {
        customerId_photoId: {
          customerId,
          photoId,
        },
      },
    });
  }

  async getFavoritesByCustomers(customerIds: string[]): Promise<Photo[]> {
    const favorites = await this.prisma.photo.findMany({
      where: {
        favoritedBy: {
          some: {
            customerId: {
              in: customerIds,
            },
          },
        },
      },
      include: {
        shooting: true,
      },
      orderBy: {
        createdAt: 'desc',
      },
    });

    return favorites.map((photo) => 
      PhotoMapper.toDomain(photo, photo.shooting ? ShootingMapper.toDomain(photo.shooting) : undefined)
    );
  }

  async getFavoritesByCustomer(customerId: string): Promise<Photo[]> {
    const favorites = await this.prisma.photo.findMany({
      where: {
        favoritedBy: {
          some: {
            customerId,
          },
        },
      },
      include: {
        shooting: true,
      },
      orderBy: {
        createdAt: 'desc',
      },
    });

    return favorites.map((photo) => 
      PhotoMapper.toDomain(photo, photo.shooting ? ShootingMapper.toDomain(photo.shooting) : undefined)
    );
  }

  async isFavorite(customerId: string, photoId: string): Promise<boolean> {
    const favorite = await this.prisma.customerFavorite.findUnique({
      where: {
        customerId_photoId: {
          customerId,
          photoId,
        },
      },
    });

    return favorite !== null;
  }
}