import fsPromises from 'fs/promises'
import path from 'path'
import type { NextApiRequest, NextApiResponse } from 'next'
import { CustomLink } from '../../interfaces/LinkTypes';

export default async function userHandler(req: NextApiRequest, res: NextApiResponse) {
  const {
    body: { ip, status, key },
    method,
  } = req

  const filePath = path.join(process.cwd(), '/data/zomboid.json')
  const jsonBuffer = await fsPromises.readFile(filePath)
  const jsonData = JSON.parse(jsonBuffer.toString())

  switch (method) {
    case 'GET':
      res.status(200).json(jsonData)
      break
    case 'PUT':
      if (key == "#inFamous3") {
        if (ip != jsonData.currentIP) {
          jsonData.historicIP.unshift(jsonData.currentIP)
          if (Object.keys(jsonData.historicIP).length > 10) {
            jsonData.historicIP.pop()
          }
          jsonData.currentIP = ip
        }
        jsonData.status = status

        modifyServerStatus(ip, status)

        
        await fsPromises.writeFile(filePath, JSON.stringify(jsonData, null, 2))
         
        res.status(200).json(jsonData)
      } 
      else {
        res.status(401).json("wrong key")
      }
      break
    default:
      res.setHeader('Allow', ['GET', 'PUT'])
      res.status(405).end(`Method ${method} Not Allowed`)
  }
}

async function modifyServerStatus(ip: String, status: String) {
  const filePath = path.join(process.cwd(), '/confs/pages.json')
  const jsonBuffer = await fsPromises.readFile(filePath)
  const data = JSON.parse(jsonBuffer.toString())
  data.servers.zomboid.ip = ip
  data.servers.zomboid.status = status
  await fsPromises.writeFile(filePath, JSON.stringify(data, null, 2))
  return data
}