<?php

namespace App\Services\Preferences;

use App\Models\Preferences;
use Illuminate\Support\Facades\DB;

class PreferencesCommandService
{
    public function __construct(private PreferencesOptionsService $options)
    {
    }

    public function upsert(int $userId, array $payload): Preferences
    {
        $data = $this->mapPayload($payload);
        $data['user_id'] = $userId;

        return DB::transaction(function () use ($userId, $data) {
            $existing = Preferences::query()->where('user_id', $userId)->first();

            if ($existing) {
                $existing->fill($data);
                $existing->save();
                return $existing->refresh();
            }

            return Preferences::query()->create($data);
        });
    }

    public function delete(Preferences $preferences): bool
    {
        return (bool) $preferences->delete();
    }

    private function mapPayload(array $payload): array
    {
        $email = $payload['receive_email_notifications'] ?? $payload['notification_email'] ?? null;
        $sms = $payload['receive_sms_notifications'] ?? $payload['notification_sms'] ?? null;

        $style = $this->options->normalizeStyle($payload['style_color'] ?? null);
        $menu = $this->options->normalizeMenu($payload['menu_color'] ?? null);

        $data = [
            'notification_email' => $email !== null ? (int) filter_var($email, FILTER_VALIDATE_BOOLEAN) : null,
            'notification_sms' => $sms !== null ? (int) filter_var($sms, FILTER_VALIDATE_BOOLEAN) : null,
            'theme' => $payload['theme'] ?? null,
            'language' => $payload['language'] ?? null,
            'style_color' => $style,
            'menu_color' => $menu,
        ];

        return array_filter($data, static fn ($value) => $value !== null);
    }
}
