/**
 * Row serializers for the projects module.
 *
 * Converts DB rows (DATE / NUMERIC / TIMESTAMPTZ types) to JSON-safe shapes:
 *  - TIMESTAMPTZ   → ISO 8601 string
 *  - DATE          → 'YYYY-MM-DD' string
 *  - NUMERIC       → JS number (parseFloat; null stays null)
 *
 * Route files import these from @zync/db/queries or @zync/db/serialize —
 * no raw Drizzle in route handlers.
 */
import type { ProjectRow, ProjectMemberRow, RetainerMonthRow } from '../schema/projects'
import type {
  ProjectObject,
  ProjectMemberObject,
  RetainerMonthObject,
  ProjectStatus,
  ProjectBillingType,
  ProjectMemberRole,
  BillingConfig,
} from '@zync/types'

export function serializeProject(row: ProjectRow): ProjectObject {
  return {
    id: row.id,
    tenant_id: row.tenantId,
    customer_id: row.customerId ?? null,
    customer_name: 'customerName' in row ? (row.customerName as string | null) : null,
    name: row.name,
    description: row.description ?? null,
    status: row.status as ProjectStatus,
    billing_type: row.billingType as ProjectBillingType,
    billing_config: (row.billingConfig as BillingConfig | null) ?? null,
    currency: row.currency,
    start_date: row.startDate ?? null,
    end_date: row.endDate ?? null,
    created_by: row.createdBy,
    created_at: row.createdAt.toISOString(),
    updated_at: row.updatedAt.toISOString(),
    completed_at: row.completedAt?.toISOString() ?? null,
    archived_at: row.archivedAt?.toISOString() ?? null,
  }
}

export function serializeProjectMember(row: ProjectMemberRow): ProjectMemberObject {
  return {
    project_id: row.projectId,
    user_id: row.userId,
    tenant_id: row.tenantId,
    user_name: 'userName' in row ? (row.userName as string | null) : null,
    user_email: 'userEmail' in row ? (row.userEmail as string | null) : null,
    role: row.role as ProjectMemberRole,
    hourly_rate: row.hourlyRate !== null && row.hourlyRate !== undefined
      ? parseFloat(String(row.hourlyRate))
      : null,
    created_at: row.createdAt.toISOString(),
  }
}

export function serializeRetainerMonth(row: RetainerMonthRow): RetainerMonthObject {
  return {
    id: row.id,
    project_id: row.projectId,
    tenant_id: row.tenantId,
    month: row.month,
    hours_included: row.hoursIncluded !== null && row.hoursIncluded !== undefined
      ? parseFloat(String(row.hoursIncluded))
      : null,
    hours_used: parseFloat(String(row.hoursUsed ?? '0')),
    hours_rolled_over: parseFloat(String(row.hoursRolledOver ?? '0')),
    invoice_triggered_at: row.invoiceTriggeredAt?.toISOString() ?? null,
    created_at: row.createdAt.toISOString(),
  }
}
