import { NextRequest, NextResponse } from 'next/server'
import { cronTaskRepo } from '@/lib/database/repositories/cron-task.repo'
import { getCronEngine } from '@/lib/cron/engine'
import { isAuthError, requireUser } from '@/lib/auth/session'

type CronTaskUpdatable = NonNullable<Parameters<typeof cronTaskRepo.updateFields>[2]>

export async function GET(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  let user
  try { user = await requireUser() } catch (err) { if (isAuthError(err)) return err; throw err }
  const { id } = await params
  const row = cronTaskRepo.findByIdAndOwner(id, user.id)
  if (!row) return NextResponse.json({ error: 'Not found' }, { status: 404 })
  return NextResponse.json(row)
}

export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  let user
  try { user = await requireUser() } catch (err) { if (isAuthError(err)) return err; throw err }
  const { id } = await params

  const existing = cronTaskRepo.findByIdAndOwner(id, user.id)
  if (!existing) return NextResponse.json({ error: 'Not found' }, { status: 404 })

  const body = await req.json()

  const fields: CronTaskUpdatable = {}
  if (body.name !== undefined) fields.name = body.name
  if (body.schedule !== undefined) fields.schedule = body.schedule
  if (body.action !== undefined) fields.action = body.action
  if (body.action_type !== undefined) fields.actionType = body.action_type
  if (body.agent_name !== undefined) fields.agentName = body.agent_name
  if (body.skill_name !== undefined) fields.skillName = body.skill_name
  if (body.workspace_id !== undefined) fields.workspaceId = body.workspace_id
  if (body.enabled !== undefined) fields.enabled = body.enabled ? 1 : 0
  if (body.config !== undefined) {
    fields.config = typeof body.config === 'object' ? JSON.stringify(body.config) : body.config
  }
  if (body.last_run_at !== undefined) fields.lastRunAt = body.last_run_at
  if (body.last_run_result !== undefined) fields.lastRunResult = body.last_run_result
  if (body.webhook_enabled !== undefined) fields.webhookEnabled = body.webhook_enabled ? 1 : 0

  if (Object.keys(fields).length === 0) {
    return NextResponse.json({ error: 'No fields to update' }, { status: 400 })
  }

  const updated = cronTaskRepo.updateFields(id, user.id, fields)

  // Auto-start cron engine when a task is enabled
  if (body.enabled === true || body.enabled === 1) {
    const engine = getCronEngine()
    if (!engine.isRunning()) engine.start()
  }

  return NextResponse.json(updated)
}

export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  let user
  try { user = await requireUser() } catch (err) { if (isAuthError(err)) return err; throw err }
  const { id } = await params

  const isHeartbeat = cronTaskRepo.findHeartbeatFlagByIdAndOwner(id, user.id)
  if (isHeartbeat) {
    return NextResponse.json({ error: 'Cannot delete heartbeat task' }, { status: 400 })
  }

  cronTaskRepo.deleteByIdAndOwner(id, user.id)
  return NextResponse.json({ ok: true })
}
