import prisma from '../services/prisma.js';
import asyncHandler from '../utils/asyncHandler.js';
import ApiError from '../utils/ApiError.js';
import { vendorSchema } from '../utils/validators.js';
import slugify from '../utils/slug.js';

export const listVendors = asyncHandler(async (_req, res) => {
  const vendors = await prisma.vendor.findMany({
    orderBy: { name: 'asc' },
    include: { _count: { select: { courses: true } } },
  });
  res.json({ success: true, vendors });
});

export const getVendor = asyncHandler(async (req, res) => {
  const vendor = await prisma.vendor.findUnique({
    where: { slug: req.params.slug },
    include: {
      courses: {
        where: { published: true },
        orderBy: { title: 'asc' },
        include: { _count: { select: { questions: true } } },
      },
    },
  });
  if (!vendor) throw ApiError.notFound('Vendor not found');
  res.json({ success: true, vendor });
});

// ---- Admin ----
export const createVendor = asyncHandler(async (req, res) => {
  const data = vendorSchema.parse(req.body);
  const vendor = await prisma.vendor.create({
    data: {
      name: data.name,
      slug: slugify(data.name),
      description: data.description || null,
      logoUrl: data.logoUrl || null,
    },
  });
  res.status(201).json({ success: true, vendor });
});

export const updateVendor = asyncHandler(async (req, res) => {
  const data = vendorSchema.partial().parse(req.body);
  const patch = { ...data };
  if (data.name) patch.slug = slugify(data.name);
  if (data.logoUrl === '') patch.logoUrl = null;
  const vendor = await prisma.vendor.update({ where: { id: req.params.id }, data: patch });
  res.json({ success: true, vendor });
});

export const deleteVendor = asyncHandler(async (req, res) => {
  await prisma.vendor.delete({ where: { id: req.params.id } });
  res.json({ success: true, message: 'Vendor deleted' });
});
