<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Finance\StoreFinanceAccountRequest;
use App\Http\Requests\Finance\UpdateFinanceAccountRequest;
use App\Models\FinanceAccount;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class FinanceAccountController extends Controller
{
    private function mapPayload(array $payload): array
    {
        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 = FinanceAccount::query()
            ->where('user_id', $userId)
            ->orderBy('code')
            ->get();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        $item->delete();

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