// import directus from '~/lib/directus'
export const getStaticPaths = async () => {
  const url = new URL(`${process.env.NEXT_PUBLIC_DIRECTUS_API_URL}/items/vendors`)
  url.searchParams.append('fields[]', 'slug')
  url.searchParams.append('limit', -1)
  const res = await fetch(url.toString())

  const { data: vendors } = await res.json()

  return {
    paths: vendors.map((v) => ({ params: { slug: v.slug } })),
    fallback: false, // false or "blocking"
  }
}

export const getStaticProps = async ({ params: { slug } }) => {
  const url = new URL(`${process.env.NEXT_PUBLIC_DIRECTUS_API_URL}/items/vendors`)
  url.searchParams.append('fields[]', '*')
  url.searchParams.append('fields[]', 'categories.categories_id.slug')
  url.searchParams.append('fields[]', 'categories.categories_id.name')
  url.searchParams.append('fields[]', 'categories.categories_id.parent_id')
  url.searchParams.append('fields[]', 'categories.categories_id.subcategories.slug')
  url.searchParams.append('fields[]', 'categories.categories_id.subcategories.name')
  url.searchParams.append('limit', 1)
  url.searchParams.append('filter', JSON.stringify({ slug: { _eq: slug } }))

  const res = await fetch(url.toString())

  const {
    data: [vendor],
  } = await res.json()

  return { props: vendor }
}

export default function VendorPage(vendor) {
  return (
    <>
      <h1>{vendor.name}</h1>
      <p>{vendor.description}</p>

      <h2>Address</h2>
      <p>
        {vendor.address_line_1 && (
          <>
            {vendor.address_line_1}
            <br />
          </>
        )}
        {vendor.address_line_2 && (
          <>
            {vendor.address_line_2}
            <br />
          </>
        )}
        {vendor.city && (
          <>
            {vendor.city}
            <br />
          </>
        )}
        {vendor.state && (
          <>
            {vendor.state}
            <br />
          </>
        )}
        {vendor.country && (
          <>
            {vendor.country}
            <br />
          </>
        )}
      </p>

      {vendor.website && (
        <>
          <h2>Website</h2>
          <a href={vendor.website} target="_blank">
            {vendor.website}
          </a>
        </>
      )}

      {vendor.categories.length > 0 && (
        <>
          <h2>Categories</h2>
          <ul>
            {vendor.categories.map((cat) => (
              <li key={cat.categories_id.slug}>{cat.categories_id.name}</li>
            ))}
          </ul>
        </>
      )}
    </>
  )
}
