import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { getSessionUser } from '@/lib/auth'
import { publicOrigin } from '@/lib/app-url'
import { createPersonalRule, listRulesForUser, toViews } from '@/lib/data/auto-participant-rules'

/** My Auto-Participants (Task 6.1 / 6.2, 2026-09-30). */
export async function GET() {
  const user = await getSessionUser()
  if (!user) return NextResponse.json({ error: 'Sign in first.' }, { status: 401 })
  return NextResponse.json(await listRulesForUser(user))
}

const createSchema = z.object({
  email: z.string().trim().email(),
  first_name: z.string().trim().max(80).optional().nullable(),
  last_name: z.string().trim().max(80).optional().nullable(),
})

/** Ask someone to be my Personal Auto-Participant. The owner is always the caller (§9). */
export async function POST(req: NextRequest) {
  const user = await getSessionUser()
  if (!user) return NextResponse.json({ error: 'Sign in first.' }, { status: 401 })
  const parsed = createSchema.safeParse(await req.json().catch(() => ({})))
  if (!parsed.success) return NextResponse.json({ error: 'Enter a valid email address.' }, { status: 400 })
  const res = await createPersonalRule({ owner: user, ...parsed.data, origin: publicOrigin(req) })
  if (!res.ok) return NextResponse.json({ error: res.error }, { status: res.status ?? 400 })
  const [view] = await toViews([res.rule])
  return NextResponse.json({ ok: true, rule: view })
}
