import qs from 'qs'

const OKI_API = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:1337'
const AWTIS_POU_CHAK_PAJ = process.env.NEXT_PUBLIC_AWTIS_POU_CHAK_PAJ || 6
const readToken = process.env.NEXT_PUBLIC_READ_TOKEN || 'read-token'

const headers = {
  next: {revalidate: 60},
  headers: {
    Authorization: `Bearer ${readToken}`
  }
}

async function request(url, opts = {}) {
  const {...options} = opts

  let res
  try {
    res = await fetch(`${OKI_API}${url}`, options)
  } catch {
    throw new Error('Eshwe pu jwenn done-a')
  }

  if (!res.ok) {
    throw new Error('Eshwe pu jwenn done-a')
  }

  return res.json()
}

export async function jwennTeksEpiSlug(slug) {
  const query = qs.stringify({
    populate: {
      user: {
        fields: ['username']
      },
      userAdmin: {
        fields: ['username', 'firstname']
      },
      commentaires: {
        fields: [
          'contenu',
          'datePublication',
          'origine',
          'auteurNom',
          'auteurHandle',
          'auteurAvatarUrl',
          'auteurProfilUrl',
          'remoteUrl'
        ],
        populate: {
          user: {
            fields: ['username']
          }
        }
      },
      couverture: {
        populate: '*'
      },
      files: {
        populate: '*'
      },
      artistes: {
        fields: ['alias', 'slug', 'musicBrainzUrl'],
      },
      streamAudio: {
        populate: '*'
      },
      streamVideo: {
        populate: '*'
      },
      kits: {
        populate: '*'
      },
      traductions: {
        populate: '*'
      },
      pawol: {
        populate: '*'
      },
      sourceOriginale: {
        fields: ['titre', 'slug', 'annee'],
        populate: {
          artistes: {
            fields: ['alias', 'slug']
          }
        }
      },
      remixes: {
        fields: ['titre', 'slug', 'annee'],
        populate: {
          artistes: {
            fields: ['alias', 'slug']
          }
        }
      }
    },
    filters: {
      slug: {
        $eq: slug
      }
    }
  }, {
    encodeValuesOnly: true
  })

  const {data} = await request(`/paroles?${query}`, headers)
  return data[0]
}

export async function jwennAwtisEpiSlug(slug) {
  const query = qs.stringify({
    populate: ['paroles', 'photo', 'paroles.couverture', 'titrePhare', 'titrePhare.streamAudio', 'titrePhare.streamVideo', 'titrePhare.couverture', 'rezoSosyal'],
    filters: {
      slug: {
        $eq: slug
      }
    }
  }, {
    encodeValuesOnly: true
  })

  const {data, meta} = await request(`/artistes?${query}`, headers)

  return {data: data[0], meta}
}

export async function jwennAwtisPajinasyon(paj) {
  const start = AWTIS_POU_CHAK_PAJ * (paj - 1)
  const query = qs.stringify({
    populate: ['paroles', 'photo'],
    sort: ['isExclusiveArtist:desc', 'createdAt:desc'],
    pagination: {
      start,
      limit: AWTIS_POU_CHAK_PAJ
    }
  }, {
    encodeValuesOnly: true
  })

  const {data, meta} = await request(`/artistes?${query}`, headers)

  return {data, meta}
}

export async function jwennToutAwtis() {
  const query = qs.stringify({
    populate: ['photo'],
    sort: ['alias:asc'],
    pagination: {
      pageSize: 200
    }
  }, {
    encodeValuesOnly: true
  })

  const data = await request(`/artistes?${query}`, headers)
  return data
}

export async function jwennTeks() {
  const query = qs.stringify({
    populate: {
      couverture: {
        populate: '*'
      },
      artistes: {
        fields: ['alias', 'slug']
      }
    },
    sort: ['titre:asc'],
    pagination: {
      pageSize: 200
    }
  }, {
    encodeValuesOnly: true
  })

  const {data} = await request(`/paroles?${query}`, headers)
  return data
}

async function jwennTouSlug(endpoint) {
  const pageSize = 200
  const slugs = []
  let page = 1
  let hasMore = true

  while (hasMore) {
    const query = qs.stringify({
      sort: ['createdAt:desc'],
      fields: ['slug'],
      pagination: {page, pageSize}
    }, {
      encodeValuesOnly: true
    })

    // eslint-disable-next-line no-await-in-loop -- pagination séquentielle, chaque page dépend du nombre de résultats de la précédente
    const {data} = await request(`/${endpoint}?${query}`, headers)
    slugs.push(...data.map(({slug}) => slug))
    hasMore = data.length === pageSize
    page += 1
  }

  return slugs
}

export async function jwennAwtisSlug() {
  return jwennTouSlug('artistes')
}

export async function jwennTeksSlug() {
  return jwennTouSlug('paroles')
}

export async function jwennDenyeTeks() {
  const query = qs.stringify({
    populate: ['artistes', 'couverture'],
    sort: ['createdAt:desc'],
    pagination: {
      limit: 6
    }
  }, {
    encodeValuesOnly: true
  })

  const {data} = await request(`/paroles?${query}`, headers)

  return data
}

export async function jwennAnVedette() {
  const query = qs.stringify({
    populate: ['artistes', 'couverture'],
    filters: {
      isNewRelease: {$eq: true}
    },
    pagination: {limit: 1}
  }, {
    encodeValuesOnly: true
  })

  const {data} = await request(`/paroles?${query}`, {
    next: {revalidate: 0},
    headers: {Authorization: `Bearer ${readToken}`}
  })

  return data?.[0] ?? null
}

export async function jwennAnTeks(teksId, token) {
  const headers = {
    'content-type': 'application/json',
    Authorization: `Bearer ${token}`
  }

  const data = await request(`/paroles/${teksId}`, {headers})
  return data
}

export async function jwennKomanteEpiTeksId(teksId) {
  const query = qs.stringify({
    sort: ['createdAt:desc'],
    populate: ['paroles', 'user'],
    filters: {
      parole: {
        id: {
          $eq: teksId
        }
      }
    }
  }, {
    encodeValuesOnly: true
  })

  const data = await request(`/commentaires?${query}`, headers)
  return data
}

export async function jwennUserEpiToken(userToken) {
  const data = await request('/users/me', {
    headers: {
      Authorization: `Bearer ${userToken}`
    }
  })

  return data
}

export async function jwennUserEpiUsername(username) {
  const query = qs.stringify({
    filters: {
      username: {
        $eq: username
      }
    }
  }, {
    encodeValuesOnly: true
  })

  const data = await request(`/users?${query}`, headers)
  return data[0]
}

export async function jwennUserEpiEmail(email) {
  const query = qs.stringify({
    filters: {
      email: {
        $eq: email
      },
      confirmed: {
        $eq: false
      },
      blocked: {
        $eq: false
      }
    }
  }, {
    encodeValuesOnly: true
  })

  const data = await request(`/users?${query}`, headers)
  return data[0]
}

export async function passwordRequest(lyen, email) {
  await request(`/auth/${lyen}`, {
    method: 'POST',
    body: {email}
  })
}

export async function jwennStats() {
  return request('/stats', {next: {revalidate: 60}})
}
