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

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

// App sign-in, step 2: swaps a correct code for an API key the app keeps.
export const Route = createFileRoute('/api/v1/auth/verify')({
  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_code', 'Enter the 6-digit code from the text message.', 422)
        const result = await verifyLoginCode(parsed.data.phone, parsed.data.code, request.headers.get('user-agent'))
        return apiJson({
          ok: true,
          data: { api_key: result.key, key_name: result.keyName, email: result.email, name: result.name },
        })
      }),
    },
  },
})
