const { PrismaClient } = require("@prisma/client");

const prisma = new PrismaClient();

async function diagnoseDatabase() {
  try {
    console.log("🔍 ДИАГНОСТИКА БАЗЫ ДАННЫХ...\n");

    // Проверяем пользователей
    const users = await prisma.user.findMany({
      include: {
        organization: true,
      },
    });

    console.log("👥 ПОЛЬЗОВАТЕЛИ:");
    users.forEach((user) => {
      console.log(`  - ID: ${user.id}`);
      console.log(`    Телефон: ${user.phone}`);
      console.log(`    Организация: ${user.organization?.name || "НЕТ"}`);
      console.log(`    Тип организации: ${user.organization?.type || "НЕТ"}`);
      console.log("");
    });

    // Проверяем организации
    const organizations = await prisma.organization.findMany();
    console.log("🏢 ОРГАНИЗАЦИИ:");
    organizations.forEach((org) => {
      console.log(`  - ID: ${org.id}`);
      console.log(`    Название: ${org.name}`);
      console.log(`    Тип: ${org.type}`);
      console.log("");
    });

    // Проверяем товары
    const products = await prisma.product.findMany({
      include: {
        organization: true,
        category: true,
      },
      orderBy: {
        createdAt: "desc",
      },
    });

    console.log("🛍️ ТОВАРЫ:");
    if (products.length === 0) {
      console.log("  НЕТ ТОВАРОВ В БАЗЕ ДАННЫХ");
    } else {
      products.forEach((product) => {
        console.log(`  - ID: ${product.id}`);
        console.log(`    Название: ${product.name}`);
        console.log(`    Артикул: ${product.article}`);
        console.log(`    Тип: ${product.type}`);
        console.log(`    Активен: ${product.isActive}`);
        console.log(
          `    Организация: ${product.organization?.name || "НЕТ"} (${
            product.organization?.type || "НЕТ"
          })`
        );
        console.log(`    Создан: ${product.createdAt}`);
        console.log("");
      });
    }

    // Проверяем товары поставщиков
    const wholesaleProducts = await prisma.product.findMany({
      where: {
        organization: {
          type: "WHOLESALE",
        },
        type: "PRODUCT",
      },
      include: {
        organization: true,
      },
    });

    console.log("🏪 ТОВАРЫ ПОСТАВЩИКОВ (WHOLESALE + PRODUCT):");
    if (wholesaleProducts.length === 0) {
      console.log("  НЕТ ТОВАРОВ ПОСТАВЩИКОВ");
    } else {
      wholesaleProducts.forEach((product) => {
        console.log(
          `  - ${product.name} (${product.article}) - ${product.organization?.name}`
        );
      });
    }
  } catch (error) {
    console.error("❌ ОШИБКА:", error);
  } finally {
    await prisma.$disconnect();
  }
}

diagnoseDatabase();
