
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') });

async function createQaUser() {
    try {
        const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/clinic-management';
        await mongoose.connect(mongoUri);
        console.log('Connected to MongoDB');

        // 1. Ensure Plan
        let plan = await Plan.findOne({ title: 'QA Plan' });
        if (!plan) {
            console.log('Creating QA Plan...');
            plan = new Plan({
                title: 'QA Plan',
                price: 0,
                period: 'monthly',
                features: ['All Features']
            });
            await plan.save();
        }

        // 2. Ensure User
        const email = 'qa@clinic.com';
        const normalizedEmail = email.toLowerCase();
        let user = await User.findOne({ email: normalizedEmail });

        if (!user) {
            console.log('Creating new user...');
            user = new User({
                firstName: 'QA',
                lastName: 'Tester',
                email: email,
                password: 'TestPassword123!', // Will be hashed by pre-save
                userType: 'doctor',
                isActive: true
            });
            await user.save();
            console.log('User created.');
        } else {
            console.log('User exists, updating password...');
            user.password = 'TestPassword123!';
            await user.save();
            console.log('User updated.');
        }

        // 3. Ensure Subscription
        const existingSub = await Subscription.findOne({ userId: user._id });
        if (!existingSub) {
            console.log('Creating subscription...');
            const sub = new Subscription({
                userId: user._id,
                planId: plan._id,
                startDate: new Date(),
                endDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 days
                status: 'Active',
                category: 'Medical',
                autoRenew: false
            });
            await sub.save();
            console.log('Subscription created.');
        } else {
            console.log('Subscription exists, updating...');
            existingSub.status = 'Active';
            existingSub.endDate = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
            await existingSub.save();
            console.log('Subscription updated.');
        }

    } catch (err) {
        console.error(err);
    } finally {
        await mongoose.disconnect();
    }
}

createQaUser();
