<?php

declare(strict_types=1);

namespace App\Http\Resources;

use App\Models\Household;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

/**
 * @mixin Household
 */
class HouseholdResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'branch' => $this->whenLoaded('branch', fn () => [
                'id' => $this->branch->id,
                'name' => $this->branch->name,
                'code' => $this->branch->code,
            ]),
            'name' => $this->name,
            'head_member' => $this->whenLoaded('headMember', fn () => $this->headMember ? [
                'id' => $this->headMember->id,
                'full_name' => trim("{$this->headMember->first_name} {$this->headMember->last_name}"),
                'member_number' => $this->headMember->member_number,
            ] : null),
            'address' => [
                'line1' => $this->address_line1,
                'line2' => $this->address_line2,
                'city' => $this->city,
                'state_province' => $this->state_province,
                'postal_code' => $this->postal_code,
                'country' => $this->country,
            ],
            'members' => $this->whenLoaded('members', fn () => $this->members->map(fn ($member) => [
                'id' => $member->id,
                'member_number' => $member->member_number,
                'full_name' => trim("{$member->first_name} {$member->last_name}"),
                'household_role' => $member->household_role,
                'membership_status' => $member->membership_status,
                'photo_thumb_url' => $member->photo_path ? "/api/v1/members/{$member->id}/photo?size=thumb" : null,
            ])),
            'created_at' => $this->created_at?->toIso8601String(),
            'updated_at' => $this->updated_at?->toIso8601String(),
        ];
    }
}
