import path from 'path'
import fs from 'fs'
import { configService } from './ConfigService'
import { downloadService } from './DownloadService'

export class PhpMyAdminService {
    private pmaDir: string
    private downloadUrl = 'https://www.phpmyadmin.net/downloads/phpMyAdmin-latest-all-languages.zip'

    constructor() {
        this.pmaDir = path.join(configService.getBasePath(), 'phpmyadmin')
    }

    async isInstalled(): Promise<boolean> {
        return fs.existsSync(path.join(this.pmaDir, 'index.php'))
    }

    async setup(mariaDbPort: string, onProgress?: (progress: number) => void): Promise<boolean> {
        if (!fs.existsSync(this.pmaDir)) {
            fs.mkdirSync(this.pmaDir, { recursive: true })
        }

        try {
            await downloadService.downloadAndExtract(this.downloadUrl, 'phpmyadmin', (p) => {
                if (onProgress) onProgress(p)
            }, this.pmaDir)

            // After extraction, the zip usually contains a folder like phpMyAdmin-x.y.z-all-languages
            // We should move contents to the root of this.pmaDir if they are nested
            const items = fs.readdirSync(this.pmaDir)
            if (items.length === 1 && fs.statSync(path.join(this.pmaDir, items[0])).isDirectory()) {
                const nestedDir = path.join(this.pmaDir, items[0])
                const nestedItems = fs.readdirSync(nestedDir)
                for (const item of nestedItems) {
                    fs.renameSync(path.join(nestedDir, item), path.join(this.pmaDir, item))
                }
                fs.rmdirSync(nestedDir)
            }

            // Generate config.inc.php
            this.generateConfig(mariaDbPort)

            return true
        } catch (error) {
            console.error('phpMyAdmin setup error:', error)
            return false
        }
    }

    private generateConfig(mariaDbPort: string = '3306') {
        const configPath = path.join(this.pmaDir, 'config.inc.php')
        const blowfishSecret = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)

        const configContent = `<?php
$cfg['blowfish_secret'] = '${blowfishSecret}';
$i = 0;
$i++;
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['host'] = '127.0.0.1:${mariaDbPort}';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
$cfg['Lang'] = '';
?>`

        fs.writeFileSync(configPath, configContent)
    }

    getPath(): string {
        return this.pmaDir
    }
}

export const phpMyAdminService = new PhpMyAdminService()
