<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class LenderResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $halfCredits = ceil((integer)$this->number_credits / 2);

        $status = 0;

        switch ( (integer)$this->number_credits ) {
            case 0:
                $status = 2;
                break;
            case 1:
                if ((integer)$this->number_bad_repayments === 0) {
                    $status = 2;
                }
                break;
            default:
                if ((integer)$this->number_bad_repayments === 0) {
                    $status = 2;
                } elseif ((integer)$this->number_bad_repayments < $halfCredits) {
                    $status = 1;
                }

                break;
        }

        return [
            'id' => $this->id,
            'code' => $this->code,
            'first_name' => $this->first_name,
            'last_name' => $this->last_name,
            'name' => $this->name(),
            'email' => $this->email,
            'phone' => $this->phone,
            'count_credits' => (integer)$this->count_credits,
            'number_credits' => (integer)$this->number_credits,
            'number_bad_repayments' => (integer)$this->number_bad_repayments,
            'total_credits' => (double)$this->total_credits,
            'total_repayments' => (double)$this->total_repayments,
            'gap' => (double)$this->total_credits - (double)$this->total_repayments,
            'in_progress' => (boolean)$this->in_progress,
            'status' => $status // 0 => bad / 1 => careful / 2 => good
        ];
    }
}
