import { sequelize } from '../config/database';
import { User } from '../models/User';
import { ApiTokenService } from '../services/apiToken.service';

async function testApiTokens() {
    try {
        console.log('🔌 Connecting to database...');
        await sequelize.authenticate();
        console.log('✅ Database connected');

        const apiTokenService = new ApiTokenService();

        // 1. Find an admin user
        const adminUser = await User.findOne({ where: { role: 'ADMIN' } });
        if (!adminUser) {
            console.error('❌ No admin user found. Please seed the database first.');
            process.exit(1);
        }
        console.log(`👤 Found Admin User: ${adminUser.email}`);

        // 2. Create a Token
        console.log('🔑 Creating API Token...');
        const tokenName = 'Test Token ' + Date.now();
        const { token, apiToken } = await apiTokenService.createToken(adminUser.userId, tokenName, 30);
        console.log(`✅ Token Created: ${token}`);
        console.log(`   ID: ${apiToken.id}`);
        console.log(`   Prefix: ${apiToken.prefix}`);

        // 3. Verify Token
        console.log('🔍 Verifying Token...');
        const verifiedUser = await apiTokenService.verifyToken(token);
        if (verifiedUser && verifiedUser.userId === adminUser.userId) {
            console.log('✅ Token Verification Successful');
        } else {
            console.error('❌ Token Verification Failed');
        }

        // 4. List Tokens
        console.log('📋 Listing Tokens...');
        const tokens = await apiTokenService.listTokens(adminUser.userId);
        console.log(`✅ Found ${tokens.length} tokens`);
        const createdToken = tokens.find(t => t.id === apiToken.id);
        if (createdToken) {
            console.log('✅ Created token found in list');
        } else {
            console.error('❌ Created token NOT found in list');
        }

        // 5. Revoke Token
        console.log('🚫 Revoking Token...');
        const revoked = await apiTokenService.revokeToken(adminUser.userId, apiToken.id);
        if (revoked) {
            console.log('✅ Token Revoked Successfully');
        } else {
            console.error('❌ Token Revocation Failed');
        }

        // 6. Verify Revocation
        console.log('🔍 Verifying Revoked Token...');
        const revokedUser = await apiTokenService.verifyToken(token);
        if (!revokedUser) {
            console.log('✅ Revoked Token Verification Successful (Access Denied)');
        } else {
            console.error('❌ Revoked Token Verification Failed (Access Granted)');
        }

    } catch (error) {
        console.error('❌ Test Failed:', error);
    } finally {
        await sequelize.close();
    }
}

testApiTokens();
