import '@mantine/core/styles.css'
import '@mantine/dates/styles.css'
import 'mantine-datatable/styles.layer.css'
import '@/views/[lang]/globals.css'

import { createMiddleware, createStart } from '@tanstack/react-start'
import { redirect } from '@tanstack/react-router'
import { resolveRequestRouting } from '@/lib/request-routing'

export const startInstance = createStart(() => ({
  requestMiddleware: [
    createStartRequestMiddleware(),
  ],
}))

function createStartRequestMiddleware() {
  return createMiddleware().server(async ({ request, next }) => {
    const result = await resolveRequestRouting({
      url: request.url,
      pathname: new URL(request.url).pathname,
      search: new URL(request.url).search,
      headers: request.headers,
      cookies: new Map(
        (request.headers.get('cookie') ?? '')
          .split(';')
          .map((part) => part.trim())
          .filter(Boolean)
          .map((part) => {
            const index = part.indexOf('=')
            return [
              part.slice(0, index),
              decodeURIComponent(part.slice(index + 1)),
            ] as const
          })
      ),
    })

    if (result.type === 'redirect') {
      throw redirect({ href: result.location })
    }

    return next()
  })
}
