import prisma from '../lib/prisma';
import { getIO } from '../socket';

type NewJobNotification = {
  id: string;
  title: string;
  location: string;
  categoryId: string;
  category: { name: string };
};

export async function notifyWorkersOfNewJob(job: NewJobNotification) {
  try {
    const io = getIO();
    const workers = await prisma.workerSkill.findMany({
      where: { categoryId: job.categoryId },
      include: {
        worker: {
          include: { user: { select: { id: true } } },
        },
      },
    });

    for (const ws of workers) {
      const userId = ws.worker.user.id;

      const notification = await prisma.notification.create({
        data: {
          userId,
          type: 'JOB_POSTED',
          title: `New ${job.category.name} Job Available`,
          message: `${job.title} in ${job.location}`,
          data: { jobId: job.id, categoryId: job.categoryId },
        },
      });

      io.to(`user:${userId}`).emit('notification', notification);
      io.to(`user:${userId}`).emit('new-job', job);
    }

    io.to(`category:${job.categoryId}`).emit('new-job', job);
  } catch (e) {
    console.error('Socket notification error:', e);
  }
}
