import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'url';

async function downloadImage(url, file) {
  const resp = await fetch(url);
  if (resp.status !== 200) throw new Error(`${url} - not found`);
  const blob = await resp.blob();

  const arrayBuffer = await blob.arrayBuffer();

  const buffer = Buffer.from(arrayBuffer);

  fs.writeFileSync(file, buffer);
}

const filename = fileURLToPath(import.meta.url);
const dirname = path.dirname(filename);

const fileIconDir = path.join(dirname, '../../../../log/marker-icon');

fs.mkdirSync(fileIconDir, { recursive: true });

export default async function markerIconApi(req, reply) {
  const { params = {} } = req;
  params.data = params['*'];
  if (!params.data) {
    return reply.status(400).send('not enough params: data');
  }

  const iconPath = path.join(fileIconDir, params?.data);

  if (fs.existsSync(iconPath)) {
    const buffer = fs.readFileSync(iconPath); // works for small files same as stream, but also unit-test-friendly
    return reply.type('image/png').send(buffer);
  }

  await downloadImage(`https://data.softpro.ua/api-user/marker/${params.data}`, iconPath).catch(err => {
    return reply.status(404).send('icon not found');
  });
  return fs.createReadStream(iconPath);

}
