<?php

namespace App\Services\Admin\ProductConfigOption;

use App\Models\Admin;
use App\Models\Log;
use App\Models\ProductConfigOption;
use Illuminate\Support\Facades\DB;
use App\Services\Admin\ProductConfigOption\UsageStatsService;

class RestoreOptionService
{
    public function execute(
        ProductConfigOption $option,
        Admin $admin,
        ?string $ipAddress = null,
    ): ProductConfigOption {
        if (! $option->isArchived()) {
            throw new \DomainException('not_archived');
        }
        return DB::transaction(function () use ($option, $admin, $ipAddress) {
            Log::create([
                'type' => Log::TYPE_ADMIN,
                'observer' => $admin->name,
                'module' => 'ProductConfigOption',
                'method' => 'restored',
                'admin_id' => $admin->id,
                'ip_address' => $ipAddress ?? '0.0.0.0',
                'description' => "Restored option #{$option->id} ({$option->name})",
                'request' => ['entity_id' => $option->id],
            ]);
            $option->forceFill(['archived_at' => null])->save();
            app(UsageStatsService::class)->invalidate($option->id);
            return $option;
        });
    }
}
