<?php

namespace PloverCRM\Core\CRM\Schemas;

/**
 * Growth Schema
 * 
 * Defines the standard structure for growth/stats data
 * Format: {"date" => count, ...}
 */
class GrowthSchema
{
    /**
     * Validate growth data
     * 
     * @param array $data
     * @return array
     */
    public static function validate(array $data): array
    {
        $errors = [];

        if (!is_array($data)) {
            $errors[] = "Growth data must be an array";
            return [
                'valid' => false,
                'errors' => $errors,
            ];
        }

        foreach ($data as $date => $count) {
            // Validate date format
            if (!is_string($date) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
                $errors[] = "Invalid date format: {$date}. Expected Y-m-d format.";
            }

            // Validate count is numeric
            if (!is_numeric($count)) {
                $errors[] = "Count for date {$date} must be numeric, got " . gettype($count);
            }
        }

        return [
            'valid' => empty($errors),
            'errors' => $errors,
        ];
    }

    /**
     * Normalize growth data to standard format
     * Converts array of objects to date => count format
     * 
     * @param array $data Array of ['date' => ..., 'count' => ...] or already normalized
     * @return array Normalized as ['date' => count, ...]
     */
    public static function normalize(array $data): array
    {
        // If already in correct format (associative array with date keys)
        if (!empty($data) && isset(array_values($data)[0]) && !is_array(array_values($data)[0])) {
            return $data;
        }

        // Convert from array of objects format
        $normalized = [];
        foreach ($data as $item) {
            if (is_array($item) && isset($item['date']) && isset($item['count'])) {
                $normalized[$item['date']] = (int) $item['count'];
            }
        }

        return $normalized;
    }
}
