import { NextApiRequest, NextApiResponse } from 'next';
import fs from 'fs';
import path from 'path';

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
    const data :any = {}
    let k = 0, x = -k, y = -k, z = -k
    for (let i = 0; i<= 25000;i++){
      while (true){
        const _key = `${x},${y},${z}`
        if(!data[_key]){
          data[_key] = i
          break
        }
        z++
        if(z>k){
          y++
          z = -k
          if(y>k){
            x++
            y = z = -k
            if(x>k){
              k ++
              x = y = z = -k
            }
          }
        }
      }
    }
    // Define the path where the JSON file will be saved
    const filePath = path.join(process.cwd(), 'public', 'chunkmap.json');

    try {
      // Write the JSON data to the file
      fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
      res.status(200).json({ message: 'JSON file saved successfully!' });
    } catch (error) {
      console.error('Error saving JSON file:', error);
      res.status(500).json({ error: 'Failed to save JSON file.' });
    }
  }else if(req.method === 'GET'){
    const filePath = path.join(process.cwd(), 'public', 'chunkmap.json');
    const jsonData = fs.readFileSync(filePath, 'utf8');
    const data = JSON.parse(jsonData);
    res.status(200).json(data)
  } else {
    res.setHeader('Allow', ['POST']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}