import { createFileRoute } from '@tanstack/react-router'
import { z } from 'zod'
import { apiError, apiJson } from '@/lib/api-keys.server'
import { requestLoginCode } from '@/lib/phone-auth.server'
import { clientIp, publicHandler, readJson } from '@/lib/public-api.server'

const body = z.object({ phone: z.string().trim().min(9).max(20) })

// App sign-in, step 1: texts a 6-digit code to the number if it is saved on
// an account. The answer is the same either way.
export const Route = createFileRoute('/api/v1/auth/request-code')({
  server: {
    handlers: {
      POST: publicHandler(async (request) => {
        const json = await readJson(request)
        if (!json.ok) return json.response
        const parsed = body.safeParse(json.body)
        if (!parsed.success) return apiError('invalid_phone', 'Enter a Ghana mobile number, like 024 123 4567.', 422)
        const result = await requestLoginCode(parsed.data.phone, clientIp(request))
        return apiJson({ ok: true, data: { sent: true, expires_in: result.expiresInSeconds } })
      }),
    },
  },
})
