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

export interface Project {
    id: string
    name: string
    path: string
    phpVersion: string
    mariaDbVersion: string
    host: string
    serverType?: 'nginx' | 'apache'
}

export class ProjectService {
    private projectsFile: string
    private projects: Project[] = []

    constructor() {
        this.projectsFile = path.join(configService.getBasePath(), 'projects.json')
        this.loadProjects()
    }

    private loadProjects() {
        if (fs.existsSync(this.projectsFile)) {
            try {
                const data = fs.readFileSync(this.projectsFile, 'utf-8')
                this.projects = JSON.parse(data)
            } catch (e) {
                console.error('Failed to load projects:', e)
                this.projects = []
            }
        }
    }

    private saveProjects() {
        fs.writeFileSync(this.projectsFile, JSON.stringify(this.projects, null, 2))
    }

    getProjects(): Project[] {
        return this.projects
    }

    addProject(project: Omit<Project, 'id'>): Project {
        const newProject = {
            ...project,
            id: Date.now().toString()
        }
        this.projects.push(newProject)
        this.saveProjects()
        return newProject
    }

    updateProject(project: Project) {
        const index = this.projects.findIndex(p => p.id === project.id)
        if (index !== -1) {
            this.projects[index] = project
            this.saveProjects()
        }
    }

    removeProject(id: string) {
        this.projects = this.projects.filter(p => p.id !== id)
        this.saveProjects()
    }
}

export const projectService = new ProjectService()
