/**
 * Integration Test: Subscription Details API
 * Ensures the endpoint uses correct Prisma relation names
 *
 * Prevents regression of the billing tab issue where:
 * - Wrong relation name: billingHistory vs billing_history
 * - Wrong relation name: user vs users
 */

import { prisma } from "@/lib/db";
import { createId } from "@paralleldrive/cuid2";

// Integration test requires real database connection; mock Prisma stubs cannot
// execute chained relation queries needed here.
describe.skip("Subscription Details API - Prisma Relations", () => {
  let testUserId: string;
  let testSubscriptionId: string;

  beforeAll(async () => {
    // Create test user
    const userId = createId();
    await prisma.users.create({
      data: {
        id: userId,
        email: `test-billing-${Date.now()}@example.com`,
        name: "Test Billing User",
        password: "hashed_password",
        role: "CUSTOMER",
        onboardingComplete: true,
      },
    });

    testUserId = userId;

    // Create test subscription
    const subId = createId();
    await prisma.subscriptions.create({
      data: {
        id: subId,
        userId: testUserId,
        stripeCustomerId: `cus_test_${Date.now()}`,
        stripeSubscriptionId: `sub_test_${Date.now()}`,
        stripePriceId: "price_test",
        tierId: "tier2",
        status: "trialing",
        billingPeriod: "monthly",
        currentPeriodEnd: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 days
        trialEndsAt: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000), // 14 days
        setupFeePaid: true,
        setupFeeAmount: 50000,
        setupFeePaidAt: new Date(),
        cardBrand: "visa",
        cardLastFour: "4242",
        paymentMethodId: "pm_test",
        updatedAt: new Date(),
      },
    });

    testSubscriptionId = subId;

    // Create billing history entry
    await prisma.billing_history.create({
      data: {
        id: createId(),
        userId: testUserId,
        subscriptionId: testSubscriptionId,
        event: "checkout_completed",
        amount: 50000,
        currency: "qar",
        metadata: {},
      },
    });
  });

  afterAll(async () => {
    // Cleanup
    await prisma.billing_history.deleteMany({ where: { userId: testUserId } });
    await prisma.subscriptions.deleteMany({ where: { userId: testUserId } });
    await prisma.users.delete({ where: { id: testUserId } });
    await prisma.$disconnect();
  });

  describe("Prisma Relation Names", () => {
    it('should query subscriptions using correct "users" relation (not "user")', async () => {
      // This test ensures we use the correct relation name in WHERE clause
      const result = await prisma.subscriptions.findFirst({
        where: {
          users: {
            // ✅ Correct: "users" (matches schema)
            id: testUserId,
          },
          status: {
            in: ["active", "trialing", "past_due"],
          },
        },
      });

      expect(result).not.toBeNull();
      expect(result?.userId).toBe(testUserId);
      expect(result?.tierId).toBe("tier2");
      expect(result?.status).toBe("trialing");
    });

    it('should include "billing_history" relation (not "billingHistory")', async () => {
      // This test ensures we use the correct relation name in INCLUDE
      const result = await prisma.subscriptions.findFirst({
        where: {
          id: testSubscriptionId,
        },
        include: {
          billing_history: true, // ✅ Correct: snake_case
        },
      });

      expect(result).not.toBeNull();
      expect(result?.billing_history).toBeDefined();
      expect(Array.isArray(result?.billing_history)).toBe(true);
      expect(result?.billing_history.length).toBeGreaterThan(0);
    });

    it('should include "users" relation correctly', async () => {
      const result = await prisma.subscriptions.findFirst({
        where: {
          id: testSubscriptionId,
        },
        include: {
          users: true, // ✅ Correct: "users" relation
        },
      });

      expect(result).not.toBeNull();
      expect(result?.users).toBeDefined();
      expect(result?.users.id).toBe(testUserId);
      expect(result?.users.email).toContain("test-billing-");
    });

    it("should combine all relations correctly (full query)", async () => {
      // This is the exact query pattern used in /api/subscription/details
      const result = await prisma.subscriptions.findFirst({
        where: {
          users: {
            // ✅ Correct relation name
            id: testUserId,
          },
          status: {
            in: ["active", "trialing", "past_due"],
          },
        },
        include: {
          billing_history: {
            // ✅ Correct relation name
            orderBy: {
              createdAt: "desc",
            },
            take: 20,
          },
          users: true, // ✅ Correct relation name
        },
      });

      expect(result).not.toBeNull();
      expect(result?.users).toBeDefined();
      expect(result?.billing_history).toBeDefined();
      expect(result?.users.id).toBe(testUserId);
      expect(result?.billing_history.length).toBeGreaterThan(0);
    });
  });

  describe("Schema Regression Prevention", () => {
    it("should fail if wrong relation name is used (prevent regression)", async () => {
      // This test will fail if someone tries to use wrong names
      await expect(async () => {
        await (prisma.subscriptions.findFirst as any)({
          where: {
            user: {
              // ❌ Wrong - this should fail
              id: testUserId,
            },
          },
        });
      }).rejects.toThrow();
    });

    it("should fail if billingHistory (camelCase) is used instead of billing_history", async () => {
      await expect(async () => {
        await (prisma.subscriptions.findFirst as any)({
          where: { id: testSubscriptionId },
          include: {
            billingHistory: true, // ❌ Wrong - this should fail
          },
        });
      }).rejects.toThrow();
    });
  });

  describe("Subscription Query with User Email", () => {
    it("should find subscription by user email using correct relation", async () => {
      const user = await prisma.users.findUnique({ where: { id: testUserId } });

      const subscription = await prisma.subscriptions.findFirst({
        where: {
          users: {
            // ✅ Correct
            email: user!.email,
          },
          status: {
            in: ["active", "trialing", "past_due"],
          },
        },
        include: {
          billing_history: true, // ✅ Correct
          users: true, // ✅ Correct
        },
      });

      expect(subscription).not.toBeNull();
      expect(subscription?.users.email).toBe(user!.email);
      expect(subscription?.tierId).toBe("tier2");
      expect(subscription?.status).toBe("trialing");
      expect(subscription?.setupFeePaid).toBe(true);
    });
  });

  describe("Billing History Relation", () => {
    it("should access billing_history via snake_case", async () => {
      const subscription = await prisma.subscriptions.findFirst({
        where: { id: testSubscriptionId },
        include: { billing_history: true },
      });

      expect(subscription?.billing_history).toBeDefined();
      expect(subscription?.billing_history.length).toBeGreaterThan(0);

      const billingEvent = subscription?.billing_history[0];
      expect(billingEvent?.event).toBe("checkout_completed");
      expect(billingEvent?.amount).toBe(50000);
      expect(billingEvent?.currency).toBe("qar");
    });

    it("should map billing_history correctly in response", async () => {
      const subscription = await prisma.subscriptions.findFirst({
        where: { id: testSubscriptionId },
        include: { billing_history: true },
      });

      // Simulate what the API does
      const billingHistory = subscription?.billing_history.map((item) => ({
        id: item.id,
        event: item.event,
        amount: item.amount,
        currency: item.currency,
        createdAt: item.createdAt,
        metadata: item.metadata,
        invoiceId: item.invoiceId,
      }));

      expect(billingHistory).toBeDefined();
      expect(billingHistory?.length).toBeGreaterThan(0);
      expect(billingHistory?.[0].event).toBe("checkout_completed");
    });
  });

  describe("User Relation", () => {
    it('should access user via "users" relation (not "user")', async () => {
      const subscription = await prisma.subscriptions.findFirst({
        where: { id: testSubscriptionId },
        include: { users: true },
      });

      expect(subscription?.users).toBeDefined();
      expect(subscription?.users.id).toBe(testUserId);
      expect(subscription?.users.email).toContain("test-billing-");
    });

    it("should map users correctly in response", async () => {
      const subscription = await prisma.subscriptions.findFirst({
        where: { id: testSubscriptionId },
        include: { users: true },
      });

      // Simulate what the API does
      const user = {
        id: subscription?.users.id,
        email: subscription?.users.email,
        name: subscription?.users.name,
        companyName: subscription?.users.companyName,
      };

      expect(user.id).toBe(testUserId);
      expect(user.email).toContain("test-billing-");
      expect(user.name).toBe("Test Billing User");
    });
  });
});
