<?php

namespace App\Services\Website;

use App\Models\User;
use App\Models\Factor;
use Illuminate\Support\Facades\DB;
use App\Repositories\UserRepository;
use App\DataTransferObjects\Website\StoreInformationDTO;

class StoreInformationService
{
    public function __construct(public UserRepository $userRepository)
    {
    }

    public function __invoke(StoreInformationDTO $informationDTO): void
    {
        DB::transaction(function () use ($informationDTO) {
            $user = $this->storeUser($informationDTO);
            $userId = $user->id;
            $this->userRepository->storeSpecifications($userId, $informationDTO->specifications);
            $this->storeFactors($userId, $informationDTO);
        });
    }

    private function storeUser(StoreInformationDTO $informationDTO): User
    {
        $userInformation = $informationDTO->userInformation;

        return $this->userRepository->storeUser($userInformation, $informationDTO->planType);
    }

    private function storeFactors(int $userId, StoreInformationDTO $informationDTO): void
    {
        $factors = collect($informationDTO->factors)
            ->map(fn($row) => [
                Factor::COLUMN_UUID => $row['id'],
                Factor::COLUMN_USER_ID => $userId,
                Factor::COLUMN_DEFAULT_VALUE => $row['default_value'],
                Factor::COLUMN_VALUE => $row['value'],
            ])
            ->toArray();

        $this->userRepository->storeFactors($factors);
    }
}
