import { Request, Response } from 'express';
import { prisma } from '../../../lib/prisma';
import { AuthorRole, Prisma } from '@prisma/client';

export async function searchArticles(req: Request, res: Response) {
  try {
    const { q, author, role, date, page = 1, limit = 9 } = req.query;
    const skip = ((Number(page) || 1) - 1) * (Number(limit) || 9);

    // Подготовка условия по дате
    let dateCondition: Prisma.ArticleWhereInput = {};
    if (typeof date === 'string' && date.trim()) {
      const selectedDate = new Date(date);
      const nextDate = new Date(selectedDate);
      nextDate.setDate(selectedDate.getDate() + 1);

      dateCondition = {
        publishedAt: {
          gte: selectedDate,
          lt: nextDate,
        },
      };
    }

    // Формируем where-условие
    const where: Prisma.ArticleWhereInput = {
      ...(typeof q === 'string' && q.trim()
          ? {
            OR: [
              { title: { contains: q, mode: 'insensitive' } },
              { excerpt: { contains: q, mode: 'insensitive' } },
              { content: { contains: q, mode: 'insensitive' } },
            ],
          }
          : {}),
      ...(typeof author === 'string' && author.trim()
          ? {
            authors: {
              some: {
                authorId: author,
                ...(typeof role === 'string' && role.trim()
                    ? { role: role as AuthorRole } // 👈 проверяем и добавляем роль
                    : {}),
              },
            },
          }
          : {}),
      ...dateCondition,
    };

    // Выполнение запроса
    const [articles, total] = await Promise.all([
      prisma.article.findMany({
        where,
        include: {
          authors: {
            include: {
              author: {
                select: {
                  id: true,
                  displayName: true,
                  avatarUrl: true,
                  email: true,
                  order: true,
                },
              },
            },
          },
        },
        skip,
        take: Number(limit) || 9,
        orderBy: { publishedAt: 'desc' },
      }),
      prisma.article.count({ where }),
    ]);

    // Формирование ответа
    res.json({
      articles,
      totalPages: Math.ceil(total / (Number(limit) || 9)),
      currentPage: Number(page) || 1,
      total: total,
    });
  } catch (error) {
    console.error('Ошибка поиска по статьям:', error);
    res.status(500).json({ error: 'Серверная ошибка' });
  }
}
