<?php

namespace App\Services\Api\Actions;

use App\Models\Environments\Data;
use App\Models\Environments\Environment;
use Illuminate\Http\Request;

class DataAction implements ActionInterface
{
    public function execute(Request $request, array $payload): array
    {
        /** @var Environment $environment */
        $environment = $request->input('_environment');
        $data = $payload['data'] ?? [];

        // Buscar o crear el registro de Data para este entorno
        $environmentData = Data::where('environment_id', $environment->id)->first();

        if ($environmentData) {
            // Actualizar datos existentes
            $environmentData->update($this->mapDataFields($data));
        } else {
            // Crear nuevo registro
            $environmentData = Data::create(array_merge(
                ['environment_id' => $environment->id],
                $this->mapDataFields($data)
            ));
        }

        return [
            'received' => true,
            'environment_id' => $environment->id,
        ];
    }

    /**
     * Mapea los campos recibidos a los campos de la tabla data
     * 
     * @param array $data
     * @return array
     */
    private function mapDataFields(array $data): array
    {
        // Mapeo de campos posibles del payload a campos de la tabla
        $mapping = [
            'policyagreed' => 'policyagreed',
            'language' => 'language',
            'countrycode' => 'countrycode',
            'privacy' => 'privacy',
            'contactemail' => 'contactemail',
            'contactable' => 'contactable',
            'emailalert' => 'emailalert',
            'emailalertemail' => 'emailalertemail',
            'commnews' => 'commnews',
            'commnewsemail' => 'commnewsemail',
            'contactname' => 'contactname',
            'description' => 'description',
            'imageurl' => 'imageurl',
            'contactphone' => 'contactphone',
            'regioncode' => 'regioncode',
            'geolocation' => 'geolocation',
            'street' => 'street',
            'courses' => 'courses',
            'users' => 'users',
            'activeusers' => 'activeusers',
            'enrolments' => 'enrolments',
            'posts' => 'posts',
            'questions' => 'questions',
            'resources' => 'resources',
            'badges' => 'badges',
            'issuedbadges' => 'issuedbadges',
            'participantnumberaverage' => 'participantnumberaverage',
            'activeparticipantnumberaverage' => 'activeparticipantnumberaverage',
            'modulenumberaverage' => 'modulenumberaverage',
            'moodlerelease' => 'moodlerelease',
            'url' => 'url',
            'mobileservicesenabled' => 'mobileservicesenabled',
            'mobilenotificationsenabled' => 'mobilenotificationsenabled',
            'registereduserdevices' => 'registereduserdevices',
            'registeredactiveuserdevices' => 'registeredactiveuserdevices',
            'analyticsenabledmodels' => 'analyticsenabledmodels',
            'analyticspredictions' => 'analyticspredictions',
            'analyticsactions' => 'analyticsactions',
            'analyticsactionsnotuseful' => 'analyticsactionsnotuseful',
            'availableupdatesfetch' => 'availableupdatesfetch',
        ];

        $mapped = [];
        foreach ($mapping as $key => $field) {
            if (isset($data[$key])) {
                $mapped[$field] = $data[$key];
            }
        }

        return $mapped;
    }
}

