import { PrismaService } from '@/database/services/prisma.service';
import { Injectable } from '@nestjs/common';
import { ShootingMapper } from '../mappers/shooting.mapper';
import { Shooting } from '../domain/Shooting';
import { SearchShootingDTO } from '@studio-m/app-types';

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

  async findById(id: string): Promise<Shooting | null> {
    const shooting = await this.prisma.shooting.findUnique({
      where: {
        id,
      },
      include: {
        customer: true,
        photos: {
          orderBy: {
            order: 'asc',
          },
        },
      },
    });

    if (!shooting) {
      return null;
    }

    return ShootingMapper.toDomain(shooting);
  }

  async create(shooting: Shooting): Promise<Shooting> {
    const shootingData = ShootingMapper.toPrisma(shooting);

    const createdShooting = await this.prisma.shooting.create({
      data: shootingData,
    });

    return await this.findById(createdShooting.id);
  }

  async update(shooting: Shooting): Promise<Shooting> {
    const shootingData = ShootingMapper.toPrisma(shooting);

    const updatedShooting = await this.prisma.shooting.update({
      where: {
        id: shooting.id,
      },
      data: shootingData,
    });

    return this.findById(updatedShooting.id);
  }

  async delete(id: string): Promise<void> {
    await this.prisma.shooting.delete({
      where: {
        id: id,
      },
    });
  }

  async findAll(): Promise<Shooting[]> {
    const shootings = await this.prisma.shooting.findMany({
      include: {
        customer: true,
        photos: {
          orderBy: {
            order: 'asc',
          },
        },
      },
    });

    return shootings.map((shooting) => ShootingMapper.toDomain(shooting));
  }

  async search(params: SearchShootingDTO): Promise<Shooting[]> {
    const orderBy: Array<{ [key: string]: 'asc' | 'desc' }> =
      params.orderBy?.field && params.orderBy?.direction
        ? [{ [params.orderBy.field]: params.orderBy.direction }]
        : [{ description: 'desc' }];

    const shootings = await this.prisma.shooting.findMany({
      where: {
        customerId: params.customerIds
          ? {
              in: params.customerIds,
            }
          : undefined,
      },
      orderBy,
      include: {
        customer: true,
        photos: {
          orderBy: {
            order: 'asc',
          },
        },
      },
    });

    return shootings.map((shooting) => ShootingMapper.toDomain(shooting));
  }
}
