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

export async function GET(req: NextRequest) {
  let user
  try {
    user = await requireUser()
  } catch (err) {
    if (isAuthError(err)) return err
    throw err
  }
  const { searchParams } = new URL(req.url)
  const workspaceId = searchParams.get('workspace_id')

  const rows = cronTaskRepo.listByOwner(user.id, workspaceId ?? undefined)
  return NextResponse.json(rows)
}

export async function POST(req: NextRequest) {
  let user
  try {
    user = await requireUser()
  } catch (err) {
    if (isAuthError(err)) return err
    throw err
  }
  const body = await req.json()
  const id = crypto.randomUUID()

  const created = cronTaskRepo.create({
    id,
    ownerUserId: user.id,
    name: body.name || 'New Task',
    schedule: body.schedule || '',
    action: body.action || '',
    actionType: body.action_type || 'custom-prompt',
    agentName: body.agent_name || '',
    skillName: body.skill_name || '',
    workspaceId: body.workspace_id || '',
    enabled: body.enabled !== undefined ? (body.enabled ? 1 : 0) : 1,
    config: typeof body.config === 'string' ? body.config : JSON.stringify(body.config || {}),
    webhookEnabled: body.webhook_enabled !== undefined ? (body.webhook_enabled ? 1 : 0) : 0,
  })

  // Auto-start cron engine when a task is created (it may not have started
  // at boot if there were no enabled tasks at that time)
  const engine = getCronEngine()
  if (!engine.isRunning()) engine.start()

  return NextResponse.json(created, { status: 201 })
}
