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

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

  async findAll() {
    return this.prisma.poli.findMany({ where: { isActive: true }, include: { _count: { select: { doctors: true } } } });
  }

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

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

  async create(data: { name: string; description?: string; icon?: string }) {
    const slug = slugify.default(data.name, { lower: true, strict: true });
    return this.prisma.poli.create({ data: { ...data, slug } });
  }

  async update(id: number, data: { name?: string; description?: string; icon?: string; isActive?: boolean }) {
    const updateData: any = { ...data };
    if (data.name) {
      updateData.slug = slugify.default(data.name, { lower: true, strict: true });
    }
    return this.prisma.poli.update({ where: { id }, data: updateData });
  }

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

  async getDoctorsByPoli(slug: string) {
    const poli = await this.prisma.poli.findUnique({
      where: { slug },
      include: { doctors: { include: { doctor: true } } },
    });
    if (!poli) throw new NotFoundException('Poli not found');
    return poli.doctors.map((dp) => dp.doctor);
  }

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