<?php

namespace App\Http\Resources;

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

class NotificationResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        $entity = class_basename((string) $this->notifiable_type);
        $targetUrl = match ($entity) {
            'Meeting' => "/meetings/{$this->notifiable_id}/workspace",
            'Sprint' => "/sprints/{$this->notifiable_id}/workspace",
            'Task' => "/tasks?preview={$this->notifiable_id}",
            'Project' => "/projects/{$this->notifiable_id}",
            'ActionItem' => '/meetings',
            default => null,
        };
        $dataUrl = is_array($this->data) ? ($this->data['url'] ?? null) : null;
        if (! $targetUrl && is_string($dataUrl) && str_starts_with($dataUrl, '/')) {
            $targetUrl = $dataUrl;
        }

        return [
            'id' => $this->id,
            'type' => $this->type,
            'title' => $this->title,
            'body' => $this->body,
            'data' => $this->data,
            'message' => $this->title,
            'notifiable_type' => $this->notifiable_type,
            'notifiable_id' => $this->notifiable_id,
            'is_read' => $this->is_read,
            'read_at' => $this->read_at,
            'archived_at' => $this->archived_at,
            'entity_type' => $entity ? strtolower($entity) : null,
            'entity_id' => $this->notifiable_id,
            'target_url' => $targetUrl,
            'can_navigate' => (bool) $targetUrl,
            'preview' => [
                'title' => $this->title ?: 'اعلان',
                'body' => $this->body ?: ($this->data['message'] ?? null),
                'type' => $this->type,
            ],
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}
