<?php

namespace App\Http\Controllers\Admin\Api;

use App\Http\Controllers\Controller;
use App\Services\Reports\CostVsMarginService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * PRC-804 — Fiyat-edit ekranlarındaki inline marj rozeti için tekil
 * maliyet/satış/marj lookup'ı. Rozet, admin fiyatlarken rapora gitmeden
 * anlık "maliyet ₺X · marj %Y" gösterir.
 *
 * Route auth:sanctum grubunda; admin Bearer token ile auth edilir.
 */
class CostMarginController extends Controller
{
    public function __construct(protected CostVsMarginService $service) {}

    public function entity(Request $request): JsonResponse
    {
        $admin = $request->user();
        if (! $admin || ! $admin->can('generate reports')) {
            return response()->json(['success' => false, 'message' => 'Forbidden'], 403);
        }

        $validated = $request->validate([
            'entity_type' => 'required|in:product,domain',
            'entity_id' => 'required|integer|min:1',
            'currency_id' => 'required|integer|min:1',
            'period' => 'nullable|integer|min:1',
        ]);

        $result = $this->service->entityMargin(
            entityType: $validated['entity_type'],
            entityId: (int) $validated['entity_id'],
            currencyId: (int) $validated['currency_id'],
            period: isset($validated['period']) ? (int) $validated['period'] : null,
        );

        if ($result === null) {
            return response()->json([
                'success' => true,
                'found' => false,
            ]);
        }

        return response()->json([
            'success' => true,
            'found' => true,
            'data' => $result,
        ]);
    }
}
