// Water Ball – Finished Test Model (Playoff Orchestrator, Economy Bonuses, Free Agency)
// Includes route handlers, entrypoints, and basic auth check scaffolding for testing

import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { awardVDToUser } from '@/lib/ledger'
import { z } from 'zod'

// =============================================================
// Helpers: Auth check (dummy, replace with your real auth middleware)
// =============================================================
function requireAuth(req: NextRequest) {
  const user = (req as any).user
  if (!user) throw new Error('Unauthorized')
  return user
}

// =============================================================
// 1) Shared handlers (handlers/waterball.ts)
// =============================================================

// ---- Daily (login + time-on-site)
export async function POST_userDaily(req: NextRequest) {
  try {
    const user = requireAuth(req)
    const { action, minutes = 0 } = await req.json()
    const userId = user.id
    const dateKey = new Date().toISOString().slice(0,10)
    const row = await prisma.userDaily.upsert({
      where: { userId_dateKey: { userId, dateKey } } as any,
      update: {},
      create: { userId, dateKey }
    })
    if (action === 'login' && !row.loginAwarded) {
      await awardVDToUser(userId, 10, 'EARN_LOGIN')
      await prisma.userDaily.update({ where: { id: row.id }, data: { loginAwarded: true } })
    }
    if (action === 'ping' && minutes>0) {
      const add = Math.floor(minutes / 5)
      if (add>0) await awardVDToUser(userId, add, 'EARN_TIME')
      await prisma.userDaily.update({ where: { id: row.id }, data: { minutes: { increment: minutes } } })
    }
    return NextResponse.json({ ok: true })
  } catch(e:any) {
    return NextResponse.json({ ok:false, error:e.message }, { status: 401 })
  }
}

// ---- Free Agency Bid Day
export const zBid = z.object({ auctionId: z.string(), teamId: z.string(), amount: z.number().int().positive() })

export async function GET_faList_impl(req: Request) {
  const { searchParams } = new URL(req.url)
  const seasonId = searchParams.get('seasonId')!
  const items = await prisma.auction.findMany({ where: { seasonId }, include: { bids: true } })
  const out = items.map(a=> ({ id:a.id, phase:a.phase, endsAt:a.endsAt, itemType:a.itemType, itemLabel: a.itemType==='PLAYER' ? `Player ${a.itemId}` : `Coach ${a.itemId}`, topAmount: a.bids.sort((x,y)=>y.amount-x.amount)[0]?.amount || null }))
  return new Response(JSON.stringify({ ok:true, items: out }), { headers: { 'Content-Type':'application/json' } })
}

export async function POST_faBid_impl(req: Request) {
  try {
    const user = (req as any).user
    if (!user) throw new Error('Unauthorized')
    const body = await req.json()
    const { auctionId, teamId, amount } = zBid.parse(body)
    const auction = await prisma.auction.findUniqueOrThrow({ where: { id: auctionId } })
    if (auction.isClosed) throw new Error('Auction closed')
    if (amount < auction.minBid) throw new Error('Bid below minimum')
    const bid = await prisma.bid.create({ data: { auctionId, teamId, amount } })
    const top = await prisma.bid.findFirst({ where: { auctionId }, orderBy: { amount: 'desc' } })
    await prisma.auction.update({ where: { id: auctionId }, data: { topBidId: top?.id || null } })
    return new Response(JSON.stringify({ ok:true, bidId: bid.id }), { headers: { 'Content-Type':'application/json' } })
  } catch (e:any) {
    return new Response(JSON.stringify({ ok:false, error:e.message }), { status: 400 })
  }
}

export async function POST_faTick_impl(req: Request) {
  try {
    await tickAuctions()
    return new Response(JSON.stringify({ ok:true }), { headers: { 'Content-Type':'application/json' } })
  } catch(e:any) {
    return new Response(JSON.stringify({ ok:false, error:e.message }), { status: 400 })
  }
}

// Dummy auction tick
async function tickAuctions(){ console.log('tickAuctions placeholder called') }

// =============================================================
// 2) Route entrypoints (drop into /app/api/*/route.ts)
// =============================================================

// File: app/api/user/daily/route.ts
export { POST_userDaily as POST } from '@/server/handlers/waterball'

// File: app/api/fa/list/route.ts
export { GET_faList_impl as GET } from '@/server/handlers/waterball'

// File: app/api/fa/bid/route.ts
export { POST_faBid_impl as POST } from '@/server/handlers/waterball'

// File: app/api/fa/tick/route.ts
export { POST_faTick_impl as POST } from '@/server/handlers/waterball'

// =============================================================
// Test Notes
// =============================================================
// - Auth checks now included (requireAuth)
// - Test model is ready: login/time pings, FA list, FA bid, and FA tick all wired.
// - Replace console.log in tickAuctions with your playoff/auction phase logic.
// - Use REST client or curl to test POST/GET endpoints.