
import dotenv from 'dotenv';
import mongoose from 'mongoose';
import path from 'path';
import Plan from '../models/Plan';
import Subscription from '../models/Subscription';
import User from '../models/User';

// Load env
dotenv.config({ path: path.resolve(__dirname, '../../.env') });

const SAMPLE_USER_EMAIL = 'test-sub@example.com';
const SAMPLE_PLAN_TITLE = 'Monthly Gold Plan';

async function createSampleSubscription() {
    try {
        const mongoUri = process.env.MONGODB_URI;
        if (!mongoUri) {
            throw new Error('MONGODB_URI is not defined in .env file');
        }

        await mongoose.connect(mongoUri);
        console.log('✓ Connected to MongoDB');

        // 1. Check/Create User
        const normalizedEmail = SAMPLE_USER_EMAIL.toLowerCase();
        let user = await User.findOne({ email: normalizedEmail });
        if (!user) {
            console.log(`Creating user: ${SAMPLE_USER_EMAIL}`);
            user = await User.create({
                firstName: 'Test',
                lastName: 'Subscriber',
                email: SAMPLE_USER_EMAIL,
                password: 'password123', // Will be hashed by pre-save hook
                userType: 'doctor',
                isActive: true,
                language: 'en'
            });
            console.log(`✓ User created with ID: ${user._id}`);
        } else {
            console.log(`✓ User found: ${user.email} (${user._id})`);
        }

        // 2. Check/Create Plan
        let plan = await Plan.findOne({ period: 'monthly' });
        if (!plan) {
            console.log(`Creating plan: ${SAMPLE_PLAN_TITLE}`);
            plan = await Plan.create({
                title: SAMPLE_PLAN_TITLE,
                price: 29.99,
                period: 'monthly',
                features: ['Unlimited Patients', 'Email Support', 'Advanced Analytics']
            });
            console.log(`✓ Plan created with ID: ${plan._id}`);
        } else {
            console.log(`✓ Plan found: ${plan.title} (${plan._id})`);
        }

        // 3. Create/Update Subscription
        const startDate = new Date();
        const endDate = new Date();
        endDate.setMonth(endDate.getMonth() + 1); // 1 month from now

        const subscriptionData = {
            userId: user._id,
            planId: plan._id,
            category: 'Medical',
            startDate: startDate,
            endDate: endDate,
            status: 'Active',
            autoRenew: true
        };

        // Check if subscription already exists for this user
        let subscription = await Subscription.findOne({ userId: user._id });

        if (subscription) {
            console.log(`Updating existing subscription for user...`);
            Object.assign(subscription, subscriptionData);
            await subscription.save();
            console.log(`✓ Subscription updated: ${subscription._id}`);
        } else {
            console.log(`Creating new subscription...`);
            subscription = await Subscription.create(subscriptionData);
            console.log(`✓ Subscription created: ${subscription._id}`);
        }

        console.log('\n--- Summary ---');
        console.log(`User Email: ${user.email}`);
        console.log(`Plan: ${plan.title} (${plan.period})`);
        console.log(`Subscription Status: ${subscription.status}`);
        console.log(`Expires: ${subscription.endDate}`);

    } catch (err) {
        console.error('Error creating sample subscription:', err);
    } finally {
        await mongoose.disconnect();
        console.log('✓ Disconnected from MongoDB');
    }
}

createSampleSubscription();
