import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

export function metaApiPlugin() {
    let dropName = null

    return {
        name: 'meta-api-plugin',
        configureServer(server) {
            // Get the drop name from environment variable
            dropName = process.env.DROP_NAME

            if (!dropName) {
                console.warn('⚠️  DROP_NAME not set. CMS will not be able to load meta.json')
            } else {
                console.log(`📝 CMS connected to drop: ${dropName}`)
            }

            server.middlewares.use('/api/meta', async (req, res, next) => {
                if (!dropName) {
                    res.statusCode = 400
                    res.end(JSON.stringify({ error: 'No drop specified' }))
                    return
                }

                const metaPath = path.join(
                    __dirname,
                    '../../../drops',
                    dropName,
                    'public/meta.json'
                )

                // GET - Read meta.json
                if (req.method === 'GET') {
                    try {
                        if (!fs.existsSync(metaPath)) {
                            res.statusCode = 404
                            res.end(JSON.stringify({ error: 'meta.json not found' }))
                            return
                        }

                        const metaContent = fs.readFileSync(metaPath, 'utf-8')
                        res.setHeader('Content-Type', 'application/json')
                        res.end(metaContent)
                    } catch (err) {
                        res.statusCode = 500
                        res.end(JSON.stringify({ error: err.message }))
                    }
                    return
                }

                // POST - Write meta.json
                if (req.method === 'POST') {
                    let body = ''
                    req.on('data', (chunk) => {
                        body += chunk.toString()
                    })
                    req.on('end', () => {
                        try {
                            // Validate JSON
                            const metaData = JSON.parse(body)

                            // Write to file with pretty formatting
                            fs.writeFileSync(
                                metaPath,
                                JSON.stringify(metaData, null, 2),
                                'utf-8'
                            )

                            console.log(`✅ Updated meta.json for ${dropName}`)

                            res.setHeader('Content-Type', 'application/json')
                            res.end(JSON.stringify({ success: true }))
                        } catch (err) {
                            res.statusCode = 500
                            res.end(JSON.stringify({ error: err.message }))
                        }
                    })
                    return
                }

                // Method not allowed
                res.statusCode = 405
                res.end(JSON.stringify({ error: 'Method not allowed' }))
            })

            // Endpoint to get the current drop name
            server.middlewares.use('/api/drop-info', (req, res) => {
                res.setHeader('Content-Type', 'application/json')
                res.end(JSON.stringify({ dropName }))
            })
        },
    }
}
