/**
 * Manual Test Script: Subscription Status API
 *
 * Run with: npx tsx scripts/test-subscription-status.ts
 */

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

async function testSubscriptionStatusLogic() {
  console.log('\n=== Testing Subscription Status Logic ===\n');

  // Create test user
  const testUserId = createId();
  const testEmail = `test-${testUserId}@example.com`;

  console.log('1. Creating test user...');
  const user = await prisma.users.create({
    data: {
      id: testUserId,
      email: testEmail,
      name: 'Test User',
      stripeCustomerId: 'cus_test_manual',
      updatedAt: new Date(),
    },
  });
  console.log('✅ User created:', user.id);

  // Test 1: No subscription
  console.log('\n2. Testing user without subscription...');
  const noSubQuery = await prisma.subscriptions.findFirst({
    where: {
      userId: user.id,
      status: { in: ['active', 'trialing', 'past_due'] },
    },
  });
  console.log('   Result:', noSubQuery ? 'FAIL - Found subscription' : 'PASS - No subscription');

  // Test 2: Active subscription
  console.log('\n3. Creating active subscription...');
  const activeSubscription = await prisma.subscriptions.create({
    data: {
      id: createId(),
      userId: user.id,
      stripeCustomerId: user.stripeCustomerId!,
      stripeSubscriptionId: 'sub_test_active',
      stripePriceId: 'price_test_active',
      tierId: 'startup',
      status: 'active',
      billingPeriod: 'monthly',
      currentPeriodEnd: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
      setupFeePaid: true,
      updatedAt: new Date(),
    },
  });
  console.log('✅ Active subscription created:', activeSubscription.id);

  const activeQuery = await prisma.subscriptions.findFirst({
    where: {
      userId: user.id,
      status: { in: ['active', 'trialing', 'past_due'] },
    },
  });
  const hasActive = activeQuery?.status === 'active';
  console.log('   Result:', hasActive ? 'PASS - Active subscription found' : 'FAIL - No active subscription');

  // Test 3: Trialing subscription
  console.log('\n4. Creating trialing subscription...');
  await prisma.subscriptions.delete({ where: { id: activeSubscription.id } });
  const trialingSubscription = await prisma.subscriptions.create({
    data: {
      id: createId(),
      userId: user.id,
      stripeCustomerId: user.stripeCustomerId!,
      stripeSubscriptionId: 'sub_test_trial',
      stripePriceId: 'price_test_trial',
      tierId: 'growth',
      status: 'trialing',
      billingPeriod: 'yearly',
      currentPeriodEnd: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000),
      trialEndsAt: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000),
      setupFeePaid: false,
      updatedAt: new Date(),
    },
  });
  console.log('✅ Trialing subscription created:', trialingSubscription.id);

  const trialingQuery = await prisma.subscriptions.findFirst({
    where: {
      userId: user.id,
      status: { in: ['active', 'trialing', 'past_due'] },
    },
  });
  const hasTrialing = trialingQuery?.status === 'trialing';
  console.log('   Result:', hasTrialing ? 'PASS - Trialing subscription found' : 'FAIL - No trialing subscription');

  // Test 4: Canceled subscription should be ignored
  console.log('\n5. Testing canceled subscription...');
  await prisma.subscriptions.update({
    where: { id: trialingSubscription.id },
    data: { status: 'canceled', cancelledAt: new Date() },
  });

  const canceledQuery = await prisma.subscriptions.findFirst({
    where: {
      userId: user.id,
      status: { in: ['active', 'trialing', 'past_due'] },
    },
  });
  console.log('   Result:', !canceledQuery ? 'PASS - Canceled subscription ignored' : 'FAIL - Canceled subscription found');

  // Cleanup
  console.log('\n6. Cleaning up test data...');
  await prisma.subscriptions.deleteMany({ where: { userId: user.id } });
  await prisma.users.delete({ where: { id: user.id } });
  console.log('✅ Cleanup complete');

  console.log('\n=== Test Complete ===\n');
}

testSubscriptionStatusLogic()
  .catch((error) => {
    console.error('Test failed:', error);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
