import prisma from '../../config/database';
import { AppError } from '../../shared/middleware/errorHandler';

interface PipelineFilters {
  structure?: string;
  isActive?: boolean;
}

class PipelinesService {
  async findAll(filters: PipelineFilters = {}) {
    const where: any = {};

    if (filters.structure) {
      where.structure = filters.structure;
    }

    if (filters.isActive !== undefined) {
      where.isActive = filters.isActive;
    } else {
      where.isActive = true;
    }

    const pipelines = await prisma.pipeline.findMany({
      where,
      select: {
        id: true,
        name: true,
        nameAr: true,
        structure: true,
        stages: true,
        isActive: true,
      },
      orderBy: [{ structure: 'asc' }, { name: 'asc' }],
    });

    return pipelines;
  }

  async findById(id: string) {
    const pipeline = await prisma.pipeline.findUnique({
      where: { id },
      select: {
        id: true,
        name: true,
        nameAr: true,
        structure: true,
        stages: true,
        isActive: true,
      },
    });

    if (!pipeline) {
      throw new AppError(404, 'المسار غير موجود - Pipeline not found');
    }

    return pipeline;
  }
}

export const pipelinesService = new PipelinesService();
