import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import { tenants } from './drizzle/schema';
import { eq, isNull } from 'drizzle-orm';
import * as crypto from 'crypto';

const connectionString = process.env.DATABASE_URL || 'postgresql://postgres:postgres@localhost:5432/jumpa';
const sql = postgres(connectionString, { max: 1 });
const db = drizzle(sql);

function generateLicenseNumber(tenantName: string): string {
    const prefix = "LIC";
    // Extract a 3-letter code from the tenant name (e.g., "TSM", "SNO", "JUM")
    const words = tenantName.split(/[\s.]+/).filter(w => w.length > 0);
    let code = "UNK";
    if (words.length > 0) {
        if (words[0].length >= 3) {
            code = words[0].substring(0, 3).toUpperCase();
        } else if (words.length >= 2) {
            code = (words[0].substring(0, 2) + words[1].substring(0, 1)).toUpperCase();
        } else {
            code = words[0].toUpperCase().padEnd(3, 'X');
        }
    }
    
    // Generate a random 4-character hex string
    const randomHex = crypto.randomBytes(2).toString('hex').toUpperCase();
    
    // Get the current year
    const year = new Date().getFullYear();
    
    return `${prefix}-${code}-${randomHex}-${year}`;
}

async function main() {
    console.log('Fetching tenants without license numbers...');
    try {
        const tenantsWithoutLicense = await db.select().from(tenants).where(isNull(tenants.licenseNumber));
        console.log(`Found ${tenantsWithoutLicense.length} tenants without license numbers.`);
        
        for (const t of tenantsWithoutLicense) {
            const license = generateLicenseNumber(t.name);
            await db.update(tenants)
                .set({ licenseNumber: license })
                .where(eq(tenants.id, t.id));
            console.log(`[OK] Assigned ${license} to ${t.name}`);
        }
        
        console.log('Migration completed successfully.');
    } catch (e) {
        console.error('Error during migration:', e);
    } finally {
        await sql.end();
    }
}

main();
