<?php

namespace PloverCRM\Core\CRM\Schemas;

/**
 * Workspace Schema
 * 
 * Defines the standard structure for workspace data across all CRM providers
 */
class WorkspaceSchema
{
    /**
     * Required fields
     */
    const REQUIRED_FIELDS = ['lists', 'tags', 'custom_fields'];

    /**
     * All fields with their types
     */
    const FIELDS = [
        'lists' => 'array',
        'tags' => 'array',
        'custom_fields' => 'array',
    ];

    /**
     * Validate workspace data
     */
    public static function validate(array $data): array
    {
        $errors = [];

        foreach (self::REQUIRED_FIELDS as $field) {
            if (!isset($data[$field])) {
                $errors[] = "Required field '{$field}' is missing";
            }
        }

        // Validate lists format (should be associative array: title => id)
        if (isset($data['lists']) && !is_array($data['lists'])) {
            $errors[] = "Field 'lists' must be an array";
        }

        // Validate tags format (should be associative array: title => id)
        if (isset($data['tags']) && !is_array($data['tags'])) {
            $errors[] = "Field 'tags' must be an array";
        }

        // Validate custom_fields format (should be array of field objects)
        if (isset($data['custom_fields']) && !is_array($data['custom_fields'])) {
            $errors[] = "Field 'custom_fields' must be an array";
        }

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

    /**
     * Normalize workspace data
     */
    public static function normalize(array $data): array
    {
        return [
            'lists' => (array) ($data['lists'] ?? []),
            'tags' => (array) ($data['tags'] ?? []),
            'custom_fields' => (array) ($data['custom_fields'] ?? []),
        ];
    }
}
