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

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

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

        // Clean up previous test users
        const adminEmail = 'admin@clinic.com';
        const docEmail = 'doc@clinic.com';

        await User.deleteMany({ email: { $in: [adminEmail, docEmail] } });
        console.log('Cleaned up previous test users');

        // 1. Find the Annual Plan
        const annualPlan = await Plan.findOne({ period: 'annual' });
        if (!annualPlan) {
            console.error('Annual plan not found. Please run seedPlans.ts first.');
            process.exit(1);
        }

        // 2. Create Admin User
        const adminUser = new User({
            firstName: 'Admin',
            lastName: 'User',
            email: adminEmail,
            password: 'Password123!',
            userType: 'doctor', // Admins are doctors who own the clinic
            isActive: true,
            isDentist: true
        });
        await adminUser.save();
        console.log(`Created Admin User: ${adminEmail} (ID: ${adminUser._id})`);

        // 3. Create Doctor Profile for Admin
        const adminProfile = new Doctor({
            userId: adminUser._id,
            isDentist: true,
            licenseNumber: 'ADMIN-LIC-001',
            specialization: 'Orthodontist'
        });
        await adminProfile.save();

        // 4. Create Active Subscription for Admin
        const endDate = new Date();
        endDate.setFullYear(endDate.getFullYear() + 1); // 1 year from now

        const subscription = new Subscription({
            userId: adminUser._id,
            planId: annualPlan._id,
            startDate: new Date(),
            endDate: endDate,
            status: 'Active',
            autoRenew: true
        });
        await subscription.save();
        console.log('Created Active Annual Subscription for Admin');

        // 5. Create Secondary Doctor (Team Member)
        const docUser = new User({
            firstName: 'Team',
            lastName: 'Doctor',
            email: docEmail,
            password: 'Password123!',
            userType: 'doctor',
            isActive: true,
            ownerId: adminUser._id, // KEY: This makes them a secondary user
            isDentist: true
        });
        await docUser.save();
        console.log(`Created Team Doctor: ${docEmail} (Linked to Admin ID: ${adminUser._id})`);

        // 6. Create Doctor Profile for Team Doctor
        const docProfile = new Doctor({
            userId: docUser._id,
            isDentist: true,
            licenseNumber: 'TEAM-LIC-002',
            specialization: 'General Dentist'
        });
        await docProfile.save();

        console.log('=== Seeding Admin and Team Complete ===');
        console.log(`Admin Login: ${adminEmail} / Password123!`);
        console.log(`Doctor Login: ${docEmail} / Password123!`);

        process.exit(0);
    } catch (error) {
        console.error('Error seeding admin and team:', error);
        process.exit(1);
    }
};

seedAdminAndTeam();
