<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreLenderRequest;
use App\Http\Requests\UpdateLenderRequest;
use App\Http\Resources\LenderResource;
use App\Models\Lender;
use Illuminate\Http\Request;

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

        return LenderResource::collection(Lender::all());
    }

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

        $fields = $request->validated();

        $lender = Lender::create($fields);

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

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

        if ($lender) {
            return new LenderResource($lender);
        } else {
            return response()->json(['message' => 'Lender not found'], 404);
        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateLenderRequest $request, $id)
    {
        $this->authorize('update lenders');

        // Find lender by ID
        $lender = Lender::find($id);

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

        $fields = $request->validated();

        $lender->update($fields);

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

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        $this->authorize('delete lenders');

        // Find lender by ID
        $lender = Lender::find($id);

        if (!$lender) {
            return response()->json(['message' => 'Lender not found'], 404);
        } elseif ($lender->count_credits > 0) {
            return response()->json(['message' => 'Lender has a credit or more'], 403);
        } else {
            $lender->delete();

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