<?php

namespace App\Http\Resources;

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

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

        $status = 0;

        switch ( (integer)$this->number_loans ) {
            case 0:
                $status = 2;
                break;
            case 1:
                if ((integer)$this->number_bad_restitutions === 0) {
                    $status = 2;
                }
                break;
            default:
                if ((integer)$this->number_bad_restitutions === 0) {
                    $status = 2;
                } elseif ((integer)$this->number_bad_restitutions < $halfLoans) {
                    $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_loans' => (integer)$this->count_loans,
            'number_loans' => (integer)$this->number_loans,
            'number_bad_restitutions' => (integer)$this->number_bad_restitutions,
            'total_loans' => (double)$this->total_loans,
            'total_restitutions' => (double)$this->total_restitutions,
            'gap' => (double)$this->total_loans - (double)$this->total_restitutions,
            'status' => $status, // 0 => bad / 1 => careful / 2 => good
            'in_progress' => (boolean)$this->in_progress,
        ];
    }
}
