<?php

namespace App\Modules\Tenant\Resources;

use App\Modules\Core\Support\CompanyPermissionCatalog;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class CompanyResource extends JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'slug' => $this->slug,
            'email' => $this->email,
            'phone' => $this->phone,
            'address' => $this->address,
            'currency' => $this->currency,
            'timezone' => $this->timezone,
            'settings' => $this->settings ?? [],
            'status' => $this->status,
            'user_role' => $this->pivot?->role,
            'permissions' => CompanyPermissionCatalog::forRole($this->pivot?->role),
            'subscription' => $this->whenLoaded('activeSubscription', function (): ?array {
                if (! $this->activeSubscription) {
                    return null;
                }

                return [
                    'id' => $this->activeSubscription->id,
                    'status' => $this->activeSubscription->status,
                    'billing_cycle' => $this->activeSubscription->billing_cycle,
                    'trial_ends_at' => $this->activeSubscription->trial_ends_at,
                    'renews_at' => $this->activeSubscription->renews_at,
                    'plan' => [
                        'id' => $this->activeSubscription->plan->id,
                        'name' => $this->activeSubscription->plan->name,
                        'slug' => $this->activeSubscription->plan->slug,
                        'features' => $this->activeSubscription->plan->relationLoaded('features')
                            ? $this->activeSubscription->plan->features->map(fn ($feature): array => [
                                'id' => $feature->id,
                                'name' => $feature->name,
                                'slug' => $feature->slug,
                                'module' => $feature->module,
                            ])->values()
                            : [],
                    ],
                ];
            }),
        ];
    }
}
