/**
 * Row serializers for recurring tasks & templates — recurring-tasks-templates.
 *
 * Converts DB rows (NUMERIC / TIMESTAMPTZ types) to JSON-safe shapes:
 *  - TIMESTAMPTZ  → ISO 8601 string
 *  - NUMERIC      → JS number (parseFloat; null stays null)
 *  - TEXT[]       → string[]
 *
 * Route files import these — no raw Drizzle in route handlers.
 */
import type { RecurringTaskRow, TaskTemplateRow } from '../schema/recurring-tasks'
import type { RecurringTaskObject, TaskTemplateObject, RecurringTaskPriority } from '@zync/types'

export function serializeRecurringTask(row: RecurringTaskRow): RecurringTaskObject {
  return {
    id: row.id,
    tenant_id: row.tenantId,
    project_id: row.projectId ?? null,
    title: row.title,
    description: row.description ?? null,
    assignee_id: row.assigneeId ?? null,
    estimated_hours:
      row.estimatedHours !== null && row.estimatedHours !== undefined
        ? parseFloat(String(row.estimatedHours))
        : null,
    priority: row.priority as RecurringTaskPriority,
    labels: (row.labels ?? []) as string[],
    recurrence: row.recurrence,
    advance_days: row.advanceDays,
    status_id: row.statusId ?? null,
    is_active: row.isActive,
    created_by: row.createdBy,
    created_at: row.createdAt.toISOString(),
    last_generated_at: row.lastGeneratedAt?.toISOString() ?? null,
  }
}

export function serializeTaskTemplate(row: TaskTemplateRow): TaskTemplateObject {
  return {
    id: row.id,
    tenant_id: row.tenantId,
    name: row.name,
    title: row.title,
    description: row.description ?? null,
    estimated_hours:
      row.estimatedHours !== null && row.estimatedHours !== undefined
        ? parseFloat(String(row.estimatedHours))
        : null,
    priority: row.priority as RecurringTaskPriority,
    labels: (row.labels ?? []) as string[],
    created_by: row.createdBy,
    created_at: row.createdAt.toISOString(),
  }
}
