<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\CreateTabunganRequest;
use App\Http\Requests\UpdateTabunganRequest;
use App\Services\TabunganService;
use Illuminate\Http\Request;

class TabunganController extends Controller
{

    protected $tabunganService;

    public function __construct(TabunganService $tabunganService)
    {
        $this->tabunganService = $tabunganService;
    }

    public function index()
    {
        return $this->tabunganService->getAllTabungan();
    }

    public function create() {}

    public function store(CreateTabunganRequest $request)
    {
        try {
            $validatedData = $request->validated();

            $tabungan = $this->tabunganService->createTabungan($validatedData);
            return response()->json($tabungan, 201);
        } catch (\Exception $e) {
            return response()->json(['message' => $e->getMessage()], 400);
        }
    }

    public function show(string $id)
    {
        return $this->tabunganService->findById($id);
    }

    public function edit(string $id)
    {
        //
    }

    public function update(UpdateTabunganRequest $request, string $id)
    {
        try {
            $validatedData = $request->validated();

            $tabungan = $this->tabunganService->updateTabungan($id, $validatedData);

            if (!$tabungan) {
                return response()->json(['message' => 'Tabungan tidak ditemukan'], 404);
            }

            return response()->json($tabungan);
        } catch (\Exception $e) {
            return response()->json(['message' => $e->getMessage()], 400);
        }
    }

    public function destroy(string $id)
    {
        return $this->tabunganService->deleteTabungan($id);
    }
}
