const express = require('express');
const cors = require('cors');

const { pokemons } = require('./db.json');

const app = express();
app.use(cors());

const port = 3000;

app.get('/pokemon-types', (req, res) => {
  let types = [
    { label: 'Grass', value: 'Grass' },
    { label: 'Poison', value: 'Poison' },
    { label: 'Fire', value: 'Fire' },
    { label: 'Flying', value: 'Flying' },
    { label: 'Water', value: 'Water' },
    { label: 'Bug', value: 'Bug' },
    { label: 'Normal', value: 'Normal' },
    { label: 'Electric', value: 'Electric' },
    { label: 'Ground', value: 'Ground' },
    { label: 'Fairy', value: 'Fairy' },
    { label: 'Fighting', value: 'Fighting' },
    { label: 'Psychic', value: 'Psychic' },
    { label: 'Rock', value: 'Rock' },
    { label: 'Steel', value: 'Steel' },
    { label: 'Ice', value: 'Ice' },
    { label: 'Ghost', value: 'Ghost' },
    { label: 'Dragon', value: 'Dragon' },
  ];

  if (req.query.search) {
    types = types.filter((type) =>
      type.label.toLowerCase().includes(req.query.search.toLowerCase()),
    );
  }

  res.send(types);
});

app.get('/pokemons', (req, res) => {
  let data = pokemons;
  let total = 0;
  if (req.query.name) {
    data = data.filter((pokemon) =>
      pokemon.name.toLowerCase().includes(req.query.name.toLowerCase()),
    );
  }

  if (req.query.type) {
    data = data.filter((pokemon) => pokemon.type.includes(req.query.type));
  }

  if (req.query.idBetween) {
    const args = req.query.idBetween.split('|');
    if (args[0]) {
      data = data.filter((pokemon) => pokemon.id >= Number(args[0]));
    }
    if (args[1]) {
      data = data.filter((pokemon) => pokemon.id <= Number(args[1]));
    }
  }
  total = data.length;

  if (req.query.size) {
    let page = parseInt(req.query.page) ?? 1;
    data = data.slice((page - 1) * req.query.size, page * req.query.size);
  }
  res.append('X-Total', total);
  res.send(data);
});

app.listen(port, () => {
  console.log(`Pokemon server listening on port ${port}`);
});
