import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import * as slugify from 'slugify';

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

  async findAll() {
    return this.prisma.doctor.findMany({ include: { poli: { include: { poli: true } } } });
  }

  async findBySlug(slug: string) {
    const doctor = await this.prisma.doctor.findUnique({
      where: { slug },
      include: {
        poli: { include: { poli: true } },
        schedules: { include: { poli: true }, orderBy: [{ day: 'asc' }, { startTime: 'asc' }] },
      },
    });
    if (!doctor) throw new NotFoundException('Doctor not found');
    return doctor;
  }

  async getSchedule(doctorId: number) {
    return this.prisma.schedule.findMany({
      where: { doctorId },
      include: { poli: true },
      orderBy: [{ day: 'asc' }, { startTime: 'asc' }],
    });
  }

  async adminFindAll() {
    return this.prisma.doctor.findMany({ include: { poli: { include: { poli: true } } }, orderBy: { name: 'asc' } });
  }

  async create(data: { name: string; photo?: string; specialization?: string; education?: string; bio?: string; poliIds?: number[] }) {
    const { poliIds, ...rest } = data;
    const slug = slugify.default(rest.name, { lower: true, strict: true });
    return this.prisma.doctor.create({
      data: {
        ...rest,
        slug,
        poli: poliIds?.length ? { create: poliIds.map((poliId) => ({ poliId })) } : undefined,
      },
    });
  }

  async update(id: number, data: any) {
    const { poliIds, ...rest } = data;
    const updateData: any = { ...rest };
    if (data.name) {
      updateData.slug = slugify.default(data.name, { lower: true, strict: true });
    }
    if (poliIds) {
      updateData.poli = {
        deleteMany: {},
        create: poliIds.map((poliId: number) => ({ poliId })),
      };
    }
    return this.prisma.doctor.update({ where: { id }, data: updateData });
  }

  async remove(id: number) {
    return this.prisma.doctor.delete({ where: { id } });
  }

  async assignPoli(doctorId: number, poliId: number) {
    return this.prisma.doctorPoli.upsert({
      where: { doctorId_poliId: { doctorId, poliId } },
      update: {},
      create: { doctorId, poliId },
    });
  }

  async removePoli(doctorId: number, poliId: number) {
    return this.prisma.doctorPoli.delete({
      where: { doctorId_poliId: { doctorId, poliId } },
    });
  }
}
