import { ConflictException, Injectable } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../../common/prisma/prisma.service';
import type { CreateSaintInput, Gender } from '@vihar/shared';

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

  list(query?: { q?: string; gender?: Gender }) {
    return this.prisma.saint.findMany({
      where: {
        isActive: true,
        ...(query?.gender ? { gender: query.gender } : {}),
        ...(query?.q ? { name: { contains: query.q } } : {}),
      },
      orderBy: [{ displayOrder: 'asc' }, { name: 'asc' }],
      select: {
        saintId: true,
        name: true,
        honorific: true,
        gender: true,
        samudayId: true,
        samuday: { select: { samudayId: true, name: true } },
      },
      take: 100,
    });
  }

  async create(createdBy: number, input: CreateSaintInput) {
    try {
      return await this.prisma.saint.create({
        data: {
          name: input.name,
          honorific: input.honorific?.trim() || null,
          gender: input.gender,
          samudayId: input.samudayId ?? null,
          createdBy,
        },
        select: {
          saintId: true,
          name: true,
          honorific: true,
          gender: true,
          samudayId: true,
          samuday: { select: { samudayId: true, name: true } },
        },
      });
    } catch (e) {
      if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') {
        throw new ConflictException('A saint with this name and honorific already exists');
      }
      throw e;
    }
  }
}
