<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Finance\StoreFinanceJournalEntryRequest;
use App\Http\Requests\Finance\UpdateFinanceJournalEntryRequest;
use App\Models\FinanceJournalEntry;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class FinanceJournalEntryController extends Controller
{
    private function mapPayload(array $payload): array
    {
        if (array_key_exists('lines', $payload)) {
          $payload['lines_json'] = $payload['lines'];
          unset($payload['lines']);
        }

        if (array_key_exists('ref', $payload)) {
          $payload['ref_json'] = $payload['ref'];
          unset($payload['ref']);
        }

        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 = FinanceJournalEntry::query()
            ->where('user_id', $userId)
            ->orderByDesc('date')
            ->orderByDesc('created_at')
            ->get();

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

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

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

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

        $item = FinanceJournalEntry::create(array_merge($validated, ['user_id' => $userId]));

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

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

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

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

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

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

        $item->update($this->mapPayload($request->validated()));

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

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

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

        $item->delete();

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