<?php

namespace App\Services\Admin\ProductConfigOptionGroup;

use App\Models\Admin;
use App\Models\ClientProductConfigOptionValue;
use App\Models\Log;
use App\Models\Pricing;
use App\Models\ProductConfigOption;
use App\Models\ProductConfigOptionGroup;
use App\Models\ProductConfigOptionRelation;
use App\Models\ProductConfigOptionValue;
use Illuminate\Support\Facades\DB;

class ForceDeleteGroupService
{
    public function execute(
        ProductConfigOptionGroup $group,
        Admin $admin,
        ?string $ipAddress = null,
    ): void {
        if (! $group->isArchived()) {
            throw new \DomainException('not_archived');
        }

        if ($group->products()->exists()) {
            throw new \DomainException('has_product_relations');
        }

        $hasUnarchivedOption = ProductConfigOption::where('group_id', $group->id)
            ->whereNull('archived_at')
            ->exists();
        if ($hasUnarchivedOption) {
            throw new \DomainException('options_not_archived');
        }

        // Use direct query to bypass options() / configOptions() filter on hidden=false
        $optionIds = ProductConfigOption::where('group_id', $group->id)->pluck('id');

        $optionsWithClients = ClientProductConfigOptionValue::whereIn('option_id', $optionIds)->exists();
        if ($optionsWithClients) {
            throw new \DomainException('options_have_active_clients');
        }

        DB::transaction(function () use ($group, $admin, $optionIds, $ipAddress) {
            Log::create([
                'type' => Log::TYPE_ADMIN,
                'observer' => $admin->name,
                'module' => 'ProductConfigOptionGroup',
                'method' => 'force_deleted',
                'admin_id' => $admin->id,
                'ip_address' => $ipAddress ?? '0.0.0.0',
                'description' => "Force-deleted option group #{$group->id} ({$group->name}) with {$optionIds->count()} options",
                'request' => ['entity_id' => $group->id, 'option_ids' => $optionIds->all()],
            ]);

            $usageStats = app(\App\Services\Admin\ProductConfigOption\UsageStatsService::class);
            foreach ($optionIds as $optionId) {
                $usageStats->invalidate($optionId);
            }

            // Cascade: delete pricing rows (non-polymorphic: relation_id + type='product_config')
            Pricing::where('type', 'product_config')
                ->whereIn('relation_id', $optionIds)
                ->delete();

            // Cascade: delete option values
            ProductConfigOptionValue::whereIn('option_id', $optionIds)->delete();

            // Cascade: delete option relations
            ProductConfigOptionRelation::whereIn('option_id', $optionIds)->delete();

            // Cascade: delete options
            ProductConfigOption::whereIn('id', $optionIds)->delete();

            // Delete the group itself
            $group->delete();
        });
    }
}
