<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Finance\StoreFinanceSalesEntryRequest;
use App\Http\Requests\Finance\UpdateFinanceSalesEntryRequest;
use App\Models\Batch;
use App\Models\FinanceSalesEntry;
use App\Support\BatchKpiSnapshotService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class FinanceSalesEntryController extends Controller
{
    private function syncSnapshotScope(array $scope): void
    {
        $userId = (int) Auth::id();
        $batchId = (int) ($scope['batch_id'] ?? 0);
        $tankId = (int) ($scope['tank_id'] ?? 0);

        if ($batchId > 0) {
            $batch = Batch::query()->with('tank')->where('user_id', $userId)->find($batchId);
            if ($batch) {
                BatchKpiSnapshotService::syncBatch($batch);
            }
            return;
        }

        if ($tankId > 0) {
            $batches = Batch::query()->with('tank')->where('user_id', $userId)->where('tank_id', $tankId)->where('status', 'active')->get();
            BatchKpiSnapshotService::syncMany($batches);
        }
    }

    private function mapPayload(array $payload): array
    {
        if (array_key_exists('scope', $payload)) {
            $payload['scope_json'] = $payload['scope'];
            unset($payload['scope']);
        }

        if (array_key_exists('created_at', $payload)) {
            $payload['created_at_client'] = $payload['created_at'];
            unset($payload['created_at']);
        }

        if (array_key_exists('updated_at', $payload)) {
            $payload['updated_at_client'] = $payload['updated_at'];
            unset($payload['updated_at']);
        }

        return $payload;
    }

    public function index(): JsonResponse
    {
        $userId = Auth::id();
        $items = FinanceSalesEntry::query()
            ->where('user_id', $userId)
            ->orderByDesc('date')
            ->orderByDesc('created_at')
            ->get();

        return $this->success($items, 'Finance sales entries list');
    }

    public function store(StoreFinanceSalesEntryRequest $request): JsonResponse
    {
        $userId = Auth::id();
        $validated = $this->mapPayload($request->validated());

        $existing = FinanceSalesEntry::query()
            ->where('user_id', $userId)
            ->where('id', (string) $validated['id'])
            ->first();

        if ($existing) {
            return $this->success($existing, 'Finance sales entry already exists');
        }

        $item = FinanceSalesEntry::create(array_merge($validated, ['user_id' => $userId]));
        $this->syncSnapshotScope($item->scope);

        return $this->success($item, 'Finance sales entry created', 201);
    }

    public function show(string $id): JsonResponse
    {
        $userId = Auth::id();
        $item = FinanceSalesEntry::query()->where('user_id', $userId)->find($id);

        if (! $item) {
            return $this->error('Finance sales entry not found', null, 404);
        }

        return $this->success($item, 'Finance sales entry details');
    }

    public function update(UpdateFinanceSalesEntryRequest $request, string $id): JsonResponse
    {
        $userId = Auth::id();
        $item = FinanceSalesEntry::query()->where('user_id', $userId)->find($id);

        if (! $item) {
            return $this->error('Finance sales entry not found', null, 404);
        }

        $previousScope = $item->scope;
        $item->update($this->mapPayload($request->validated()));
        $this->syncSnapshotScope($previousScope);
        $this->syncSnapshotScope($item->scope);

        return $this->success($item, 'Finance sales entry updated');
    }

    public function destroy(string $id): JsonResponse
    {
        $userId = Auth::id();
        $item = FinanceSalesEntry::query()->where('user_id', $userId)->find($id);

        if (! $item) {
            return $this->error('Finance sales entry not found', null, 404);
        }

        $scope = $item->scope;
        $item->delete();
        $this->syncSnapshotScope($scope);

        return $this->success(null, 'Finance sales entry deleted');
    }
}
