<?php

namespace App\Http\Controllers;

use App\Http\Resources\BorrowerResource;
use App\Models\Borrower;
use App\Http\Requests\StoreBorrowerRequest;
use App\Http\Requests\UpdateBorrowerRequest;

class BorrowerController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $this->authorize('view borrowers');

        return BorrowerResource::collection(Borrower::all());
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreBorrowerRequest $request) {
        $this->authorize('store borrowers');

        $fields = $request->validated();

        $borrower = Borrower::create($fields);

        return response()->json([
            "borrower" => new BorrowerResource($borrower)
        ], 201);
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        // Find borrower by ID
        $borrower = Borrower::find($id);

        if ($borrower) {
            return new BorrowerResource($borrower);
        } else {
            return response()->json(['message' => 'Borrower not found'], 404);
        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateBorrowerRequest $request, $id)
    {
        $this->authorize('update borrowers');
        // Find borrower by ID
        $borrower = Borrower::find($id);

        if (!$borrower) {
            return response()->json(['message' => 'Borrower not found'], 404);
        }

        $fields = $request->validated();

        $borrower->update($fields);

        return response()->json(["borrower" => new BorrowerResource($borrower)], 200);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        $this->authorize('delete borrowers');
        // Find borrower by ID
        $borrower = Borrower::find($id);

        if (!$borrower) {
            return response()->json(['message' => 'Borrower not found'], 404);
        } elseif ($borrower->count_loans > 0) {
            return response()->json(['message' => 'Borrower has a loan or more'], 403);
        } else {
            $borrower->delete();

            return response()->json(['message' => 'Borrower deleted successfully'], 200);
        }
    }
}
