<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\ProductUpgradePathSyncRequest;
use App\Models\ClientProduct;
use App\Models\Product;
use App\Services\Product\UpgradePathService;
use App\Services\ProrationService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ProductUpgradePathController extends Controller
{
    public function __construct(private UpgradePathService $svc)
    {
    }

    /**
     * Save target products + downgrade credit settings for a source product.
     */
    public function sync(ProductUpgradePathSyncRequest $request, Product $product): JsonResponse
    {
        $product->update([
            'downgrade_credit_mode'         => $request->input('downgrade_credit_mode'),
            'same_product_downgrade_refund' => $request->boolean('same_product_downgrade_refund'),
            'refund_dropped_options'        => $request->boolean('refund_dropped_options'),
            'upgrades_enabled'              => $request->boolean('upgrades_enabled'),
        ]);

        $this->svc->syncPaths($product, $request->input('target_product_ids', []));

        $product->refresh();

        return response()->json([
            'message' => __('admin/products.upgrade_paths_saved'),
            'data'    => [
                'target_product_ids'            => $product->upgradeTargets()->pluck('target_product_id'),
                'downgrade_credit_mode'         => $product->downgrade_credit_mode,
                'same_product_downgrade_refund' => (bool) $product->same_product_downgrade_refund,
                'refund_dropped_options'        => (bool) $product->refund_dropped_options,
                'upgrades_enabled'              => (bool) $product->upgrades_enabled,
            ],
        ]);
    }

    /**
     * Return candidate target products (same group, active, excluding current)
     * along with currently-selected ids.
     */
    public function eligibleTargets(Product $product): JsonResponse
    {
        $candidates = Product::where('group_id', $product->group_id)
            ->where('id', '!=', $product->id)
            ->where('status', 'active')
            ->orderBy('order')
            ->orderBy('name')
            ->get(['id', 'name']);

        $selected = $product->upgradeTargets()->pluck('target_product_id')->all();

        return response()->json([
            'data' => [
                'products'     => $candidates->map(fn ($p) => ['id' => $p->id, 'name' => $p->name]),
                'selected_ids' => $selected,
            ],
        ]);
    }

    /**
     * Preview proration for a (target_product, period) selection on a service.
     */
    public function preview(Request $request, Product $product, ProrationService $proration): JsonResponse
    {
        $request->validate([
            'client_product_id' => ['required', 'integer', 'exists:client_products,id'],
            'period'            => ['required', 'integer', 'min:1'],
        ]);

        $service = ClientProduct::findOrFail($request->integer('client_product_id'));

        return response()->json([
            'data' => $proration->preview($service, $product, $request->integer('period')),
        ]);
    }
}
