import fs from 'fs';
import path from 'path';
import bcrypt from 'bcrypt';
import { db } from './db';
import { users, organizations } from '@shared/schema';

const INSTALLATION_FILE = path.join(process.cwd(), '.installed');

export interface InstallationConfig {
  databaseUrl: string;
  adminEmail: string;
  adminPassword: string;
  organizationName: string;
  siteName?: string;
}

export function isInstalled(): boolean {
  return fs.existsSync(INSTALLATION_FILE);
}

export function markAsInstalled(): void {
  const installData = {
    installedAt: new Date().toISOString(),
    version: '1.0.0',
  };
  fs.writeFileSync(INSTALLATION_FILE, JSON.stringify(installData, null, 2));
}

export async function runInstallation(config: InstallationConfig): Promise<{ success: boolean; message: string }> {
  try {
    if (isInstalled()) {
      return {
        success: false,
        message: 'Application is already installed. Delete .installed file to reinstall.',
      };
    }

    const hashedPassword = await bcrypt.hash(config.adminPassword, 10);

    const [organization] = await db.insert(organizations).values({
      name: config.organizationName,
      subscriptionTier: 'premium',
      subscriptionStatus: 'active',
    }).returning();

    await db.insert(users).values({
      email: config.adminEmail,
      password: hashedPassword,
      username: config.adminEmail.split('@')[0],
      role: 'superadmin',
      organizationId: organization.id,
    });

    markAsInstalled();

    return {
      success: true,
      message: 'Installation completed successfully! You can now log in with your admin credentials.',
    };
  } catch (error) {
    console.error('Installation error:', error);
    return {
      success: false,
      message: `Installation failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
    };
  }
}

export async function testDatabaseConnection(databaseUrl?: string): Promise<{ success: boolean; message: string }> {
  try {
    await db.select().from(users).limit(1);
    return {
      success: true,
      message: 'Database connection successful!',
    };
  } catch (error) {
    return {
      success: false,
      message: `Database connection failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
    };
  }
}

export function getInstallationStatus() {
  if (!isInstalled()) {
    return {
      installed: false,
      message: 'Application needs to be installed',
    };
  }

  try {
    const installData = JSON.parse(fs.readFileSync(INSTALLATION_FILE, 'utf-8'));
    return {
      installed: true,
      installedAt: installData.installedAt,
      version: installData.version,
    };
  } catch (error) {
    return {
      installed: false,
      message: 'Installation file corrupted',
    };
  }
}
