import { requireAdmin } from '@/lib/auth-guard'
import { prisma } from '@/lib/prisma'
import { JobsTable } from '@/components/admin/jobs-table'

export default async function AdminJobsPage() {
  await requireAdmin()

  const jobs = await prisma.claudeJob.findMany({
    orderBy: { created_at: 'desc' },
    take: 100,
    select: {
      id: true,
      kind: true,
      status: true,
      created_at: true,
      branch: true,
      pr_url: true,
      error: true,
      model_id: true,
      input_tokens: true,
      output_tokens: true,
      cache_read_tokens: true,
      cache_write_tokens: true,
      actual_thinking_tokens: true,
      requested_model: true,
      requested_thinking_budget: true,
      requested_permission_mode: true,
      user: { select: { username: true } },
      product: { select: { name: true } },
    },
  })

  const prices = await prisma.modelPrice.findMany()
  const priceMap = new Map(prices.map((p) => [p.model_id, p]))

  const jobsWithCost = jobs.map((job) => {
    const p = job.model_id ? priceMap.get(job.model_id) : undefined
    if (!p || job.input_tokens == null) return { ...job, cost_usd: null }
    const cost =
      (job.input_tokens ?? 0) * Number(p.input_price_per_1m) / 1_000_000 +
      (job.output_tokens ?? 0) * Number(p.output_price_per_1m) / 1_000_000 +
      (job.cache_read_tokens ?? 0) * Number(p.cache_read_price_per_1m) / 1_000_000 +
      (job.cache_write_tokens ?? 0) * Number(p.cache_write_price_per_1m) / 1_000_000 +
      (job.actual_thinking_tokens ?? 0) * Number(p.input_price_per_1m) / 1_000_000
    return { ...job, cost_usd: cost }
  })

  return (
    <div>
      <h1 className="text-xl font-semibold mb-4">Claude Jobs</h1>
      <JobsTable jobs={jobsWithCost} />
    </div>
  )
}
