import { PrismaClient } from '@prisma/client';
import { AuthorRole } from '@prisma/client';
import { Author } from '../types/auth';

const prisma = new PrismaClient();

export interface AuthorsResponse {
  authors: Author[];
  totalPages: number,
  currentPage: number,
  total: number;
}

export const authorService = {
  getAuthors: async (page: number, role?: string): Promise<AuthorsResponse> => {

    if (role && !Object.values(AuthorRole).includes(role as AuthorRole)) {
      throw new Error(`Недопустимая роль: ${role}`);
    }

    const pageSize = 10;

    const sortRoles = role
        ? {
          roles: {
            has: role as AuthorRole, // Prisma оператор для enum[]
          },
        }
        : {};

    const skip = page ? (page - 1) * pageSize : undefined;
    const take = page ? pageSize : undefined;

    try {
      // 0. Считаем общее количество авторов (без skip/take)
      const total = await prisma.author.count({
        where: {
          order: { not: 0 },
          ...sortRoles,
        },
      });

      // 1. Получаем авторов
      const authors = await prisma.author.findMany({
        select: {
          id: true,
          displayName: true,
          avatarUrl: true,
          bio: true,
          order: true,
          okUrl: true,
          vkUrl: true,
          websiteUrl: true,
          email: true,
          userId: true,
          isActive: true,
          roles: true,
          _count: {
            select: {
              articles: {
                where: {
                  role: role as AuthorRole,
                },
              },
            },
          },
          user: {
            select: {
              displayName: true,
            },
          }
        },
        where: {
          order: {not: 0},
          ...sortRoles, // 👈 добавляем условие по ролям
        },
        orderBy: {
          order: 'asc',
        },
        skip,
        take,
      });

      const sql = `
        SELECT "authorId", SUM("Article"."likes") AS "totalLikes"
        FROM "ArticleAuthor"
        JOIN "Article" ON "ArticleAuthor"."articleId" = "Article"."id"
        WHERE "ArticleAuthor"."role" = $1::"AuthorRole"
        GROUP BY "authorId"
      `;

      // 2. Считаем сумму лайков по авторам
      const rawLikes: { authorId: string; totalLikes: number | null }[] = await prisma.$queryRawUnsafe(sql, role);
      const likesMap = new Map(rawLikes.map(item => [item.authorId, item.totalLikes ?? 0]));

      const fullArticles = authors.map(author => ({
        id: author.id,
        displayName: author.displayName,
        avatarUrl: author.avatarUrl,
        bio: author.bio,
        order: author.order,
        okUrl: author.okUrl,
        vkUrl: author.vkUrl,
        websiteUrl: author.websiteUrl,
        email: author.email,
        articlesCount: author._count.articles, // Количество статей
        userId: author.userId,
        userDisplayName: author.user?.displayName || null,
        isActive: author.isActive,
        roles: author.roles,
        totalLikes: Number(likesMap.get(author.id) ?? 0)
      }));

      return {
        authors: fullArticles,
        totalPages: Math.ceil(total / pageSize),
        currentPage: page,
        total: total
      };
    } catch (error) {
      console.error('Ошибка получения авторов:', error);
      throw new Error('Ошибка получения авторов');
    }
  }
}
