<?php
/**
 * BookiFlex Core
 *
 * @package    BookiFlex
 * @subpackage Core
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */

declare(strict_types=1);

namespace BookiFlex\Core\ORM\Typecast;

use Cycle\ORM\Parser\CastableInterface;
use Cycle\ORM\Parser\UncastableInterface;

defined( 'ABSPATH' ) || exit;

class CustomerTypecast implements CastableInterface, UncastableInterface
{
    public function setRules(array $rules): array
    {
        return $rules;
    }

    public function cast(array $data): array
    {
        // Decode JSON metadata if exists
        $metadataRaw = $data['metadata'] ?? null;

        if ($metadataRaw === null || $metadataRaw === '') {
            $metadata = [];
        } elseif (is_string($metadataRaw)) {
            $metadata = json_decode($metadataRaw, true) ?? [];
        } else {
            $metadata = is_array($metadataRaw) ? $metadataRaw : [];
        }

        return [
            'id' => $data['id'] ?? null,
            'firstName' => $data['firstName'] ?? '',
            'lastName' => $data['lastName'] ?? '',
            'email' => $data['email'] ?? '',
            'phone' => $data['phone'] ?? '',
            'metadata' => $metadata,
            'createdAt' => $data['createdAt'] ?? null,
            'updatedAt' => $data['updatedAt'] ?? null,
        ];
    }

    public function uncast(array $data): array
    {
        // Encode metadata back to JSON for DB storage
        if (isset($data['metadata']) && is_array($data['metadata'])) {
            $data['metadata'] = json_encode($data['metadata']);
        }

        return $data;
    }
}
