import { PrismaClient } from '@prisma/client';
import { Author, User, UserPermissions } from '../types/auth';
import { JsonValue } from '@prisma/client/runtime/library';

const prisma = new PrismaClient();

export const userService = {
  getUsers: async (): Promise<User[]> => {
    try {
      const users: Array<{
        id: string;
        email: string;
        displayName: string;
        avatarUrl: string;
        bio: string | null;
        permissions: JsonValue;
        Author: { id: string } | null;
      }> = await prisma.user.findMany({
        select: {
          id: true,
          email: true,
          displayName: true,
          avatarUrl: true,
          bio: true,
          permissions: true,
          Author: {
            select: { id: true } // достаточно только id для проверки связи
          }
        },
      });

      return users.map((user) => {
        const permissions = user.permissions as unknown;

        if (isValidUserPermissions(permissions)) {
          return {
            ...user,
            permissions: permissions as UserPermissions,
            isLinkedToAuthor: !!user.Author,
          } as User & { isLinkedToAuthor: boolean };
        } else {
          throw new Error(`Invalid permissions format for user ${user.id}`);
        }
      });
    } catch (error) {
      console.error('Error fetching users:', error);
      throw new Error('Failed to fetch users');
    }
  },

  updateUserPermissions: async (
      userId: string,
      permissions: User['permissions']
  ): Promise<User> => {
    try {
      const updatedUser = await prisma.user.update({
        where: { id: userId },
        data: {
          permissions: permissions as any, // Сохраняем в базу JSON-объект
        },
        select: {
          id: true,
          email: true,
          displayName: true,
          permissions: true,
        },
      });

      // Валидируем полученные данные
      const updatedPermissions = updatedUser.permissions as unknown;

      if (isValidUserPermissions(updatedPermissions)) {
        return {
          ...updatedUser,
          permissions: updatedPermissions as UserPermissions,
        } as User;
      } else {
         throw new Error('Invalid permissions format for updated user ${userId}');
      }
    } catch (error) {
      console.error('Error updating user permissions:', error);
      throw new Error('Failed to update user permissions');
    }
  },
};

// Функция проверки структуры UserPermissions
function isValidUserPermissions(value: unknown): value is UserPermissions {
  if (typeof value !== 'object' || value === null) return false;

  const permissions = value as UserPermissions;
  return (Array.isArray(permissions.cities) && typeof permissions.categories === 'object');
}
