<?php

namespace App\Http\Resources;

use App\Facades\Site;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class ContentMigrationEntryResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        $data = [
            'id' => $this->id,
            'original_url' => $this->original_url,
            'original_parent' => $this->original_parent,
            'original_sub' => $this->original_sub,
            'original_sub_sub' => $this->original_sub_sub,
            'resolved_new_url' => $this->resolved_new_url,
            'new_url' => $this->new_url,
            'franchise' => $this->franchise ? [
                'id' => $this->franchise->id,
                'name' => $this->franchise->name,
            ] : null,
            'record_type' => $this->record_type,
            'record' => $this->producedRecordId() ? [
                'id' => $this->producedRecordId(),
                'name' => $this->producedRecord()?->name ?? $this->producedRecord()?->title ?? null,
            ] : null,
            // Absolute, viewable URL for the produced record (with access param
            // so unpublished records still render). Null when not yet processed
            // or no tenant domain is configured.
            'site_url' => $this->recordSiteUrl(),
            'template' => $this->template ? [
                'id' => $this->template->id,
                'name' => $this->template->name,
            ] : null,
            'category' => $this->category,
            'status' => $this->status,
            'redirect_url' => $this->redirect_url,
            'text_migrated' => $this->text_migrated,
            'imagery_migrated' => $this->imagery_migrated,
            'metas_ready' => $this->metas_ready,
            'target_review_date' => $this->target_review_date?->toDateString(),
            'checked' => $this->checked,
            'priority' => $this->priority,
            'owner' => $this->owner,
            'pageviews' => $this->pageviews,
            'avg_engagement' => $this->avg_engagement !== null ? (float) $this->avg_engagement : null,
            'key_events' => $this->key_events,
            'website_section' => $this->website_section,
            'comments' => $this->comments,
            'data' => $this->data,
            'page_id' => $this->page_id,
            'processed_at' => $this->processed_at?->toIso8601String(),
            'process_notes' => $this->process_notes,
        ];

        // Only include content_mapping on single-entry responses to avoid bloating list
        if ($request->has('entry_id') || $request->routeIs('*update*') || $request->routeIs('*.content-migration.show')) {
            $data['content_mapping'] = $this->content_mapping;
        } else {
            // Collections drop the large per-entry blobs (fetched origin HTML,
            // saved wizard progress) — only the process wizard reads them and
            // it always loads the entry via show.
            $data['data'] = collect($this->data ?? [])->except(['wizard', 'fetched_content'])->all();
        }

        return $data;
    }

    /**
     * The record produced when the entry was processed. Offers/new cars are
     * tracked via record_id (morph); pages via page_id.
     */
    private function producedRecord()
    {
        if ($this->record_id) {
            return $this->record;
        }
        if ($this->record_type === 'page' && $this->page_id) {
            return $this->page;
        }
        return null;
    }

    private function producedRecordId(): ?int
    {
        return $this->record_id ?: ($this->record_type === 'page' ? $this->page_id : null);
    }

    /**
     * Absolute site URL for the produced record, by type. withAccess=true so
     * draft/unpublished records are viewable from the preview link.
     */
    private function recordSiteUrl(): ?string
    {
        $record = $this->producedRecord();
        if (!$record) {
            return null;
        }

        return match ($this->record_type) {
            'offer' => Site::offerUrl($record, true),
            'new_car' => Site::newCarUrl($record, true),
            'page' => Site::pageUrl($record, true),
            default => method_exists($record, 'urlPath') ? $record->urlPath() : null,
        };
    }
}
