<?php

namespace App\Http\Resources;

use App\Models\User;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;

class PostResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     */
    public function toArray($request)
    {
        // return $this->media;
        return [
            // Core identification
            'id' => $this->id,
            'post_type' => $this->post_type,
            'status' => $this->status,



            // Content details
            'text' => $this->content_text ?? $this->post_text,
            'shared_text' => $this->shared_text,
            'external_link' => $this->external_link,
            'location' => $this->location ?? '',

            // Visual presentation
            'background' => [
                'color' => $this->background_color ?? $this->bg_color ?? '',
                'text_color' => $this->text_color ?? '',
                'font_size' => $this->font_size ?? 'normal',
                'palette_id' => $this->color_palette_id ?? 0,
            ],

            // Media information
            'media' => $this->media ? $this->formatMedia($this->media) : [],
            'gif' => $this->gif_url ? [
                'url' => $this->gif_url,
                'title' => $this->gif_title ?? '',
                'provider' => $this->gif_provider ?? '',
            ] : null,

            // Video links
            'video_links' => [
                'youtube' => $this->youtube_urls ?? '',
                'vimeo' => $this->vimeo_urls ?? '',
            ],

            // Engagement metrics
            'stats' => [
                'comments' => $this->comments_count ?? 0,
                'shares' => $this->shares_count ?? 0,
                'views' => $this->views_count ?? 0,
                'reactions' => DB::table('posts_reactions')->where('post_id', $this->id)->count() ?? 0,
                'appreciations' => $this->appreciations_count ?? 0,
                'video_views' => $this->video_views_count ?? 0,
                'reaction_counts' => [
                    'like' => DB::table('posts_reactions')->where('post_id', $this->id)->where('reaction', 1)->count(),
                    'love' => DB::table('posts_reactions')->where('post_id', $this->id)->where('reaction', 2)->count(),
                    'haha' => DB::table('posts_reactions')->where('post_id', $this->id)->where('reaction', 3)->count(),
                    'wow' => DB::table('posts_reactions')->where('post_id', $this->id)->where('reaction', 4)->count(),
                    'sad' => DB::table('posts_reactions')->where('post_id', $this->id)->where('reaction', 5)->count(),
                    'angry' => DB::table('posts_reactions')->where('post_id', $this->id)->where('reaction', 6)->count(),
                ],
                'my_reaction' => DB::table('posts_reactions')
                    ->where('post_id', $this->id)
                    ->where('user_id', Auth::id())
                    ->value('reaction'),

            ],

            // Relationships
            'author' => $this->user ? new UserShortResource($this->user) : null,
            'anonymous' => (bool)($this->is_anonymous ?? false),
            'tips_enabled' => (bool)($this->tips_enabled ?? false),
            'tags' => $this->tags ? HashtagResource::collection($this->tags) : [],
            'mentions' => $this->mentionedUsers ? UserShortResource::collection($this->mentionedUsers) : [],
            'tagged' => $this->whenLoaded('taggedUsers', function () {
                return UserShortResource::collection($this->taggedUsers);
            }),
            'poll' => $this->poll ? new PollResource($this->poll) : null,
            'fund' => $this->fund_id > 0 ? new FundingResource($this->fund) : null,

            // Contextual associations
            'group' => $this->group_id > 0 ? new GroupResource($this->group) : null,
            'page' => $this->page_id > 0 ? new PageResource($this->page) : null,
            'event' => $this->event_id > 0 ? new EventResource($this->event) : null,
            'product' => $this->product_id > 0 ? new ProductResource($this->product) : null,
            'fund' => $this->fund_id > 0 ? new FundingResource($this->fund) : null,
            'poll' => $this->poll_id > 0 ? new PollResource($this->poll) : null,
            'parent_post_id' => $this->parent_post_id ?? null,
            'parent_post_id' => $this->parent_post_id ?? null,
            'parent_post_data' => $this->parent_post_id > 0 && $this->parentPost ? new PostResource($this->parentPost) : null,
            'associations' => [
                'page' => $this->when($this->page_id > 0, function () {
                    $page = $this->page;
                    $cover = $page?->cover;

                    return [
                        'id' => $this->page_id,
                        'title' => $page?->page_title,
                        'username' => $page?->page_username,
                        'cover' => $cover ? getMedia($cover, 'cover') : null,
                    ];
                }),
                'group' => $this->when($this->group_id > 0, function () {
                    $group = $this->group;
                    $cover = $group?->cover_image;

                    return [
                        'id' => $this->group_id,
                        'name' => $group?->name ?? $group?->group_name,
                        'slug' => $group?->slug,
                        'cover' => $cover ? getMedia($cover, 'cover') : null,
                    ];
                }),
                'event' => $this->event_id ?? null,
                'product' => $this->product_id ?? null,
                'offer' => $this->offer_id ?? null,
                'fund' => $this->fund_id ? 0 : null,
            ],

            // Event details for event posts
            'event_details' => $this->post_type === 'event' && $this->event ? [
                'id' => $this->event->id,
                'name' => $this->event->name,
                'description' => $this->event->description,
                'location' => $this->event->location,
                'start_date' => $this->event->start_date,
                'start_time' => $this->event->start_time,
                'end_date' => $this->event->end_date,
                'end_time' => $this->event->end_time,
                'cover_image' => getMedia($this->event->cover_image, 'cover'),
                'event_url' => $this->event->event_url,
                'type' => $this->event->type,
                'category' => $this->event->category,
                'slug' => $this->event->slug,
                'organizer' => $this->event->organizer ? [
                    'id' => $this->event->organizer->id,
                    'name' => $this->event->organizer->username ?? $this->event->organizer->name,
                    'avatar' => getMedia($this->event->organizer->profile, 'avatar'),
                ] : null,
                'participants_count' => $this->event->participants()->count(),
                'is_going' => $this->event->isGoing(Auth::id()),
                'is_interested' => $this->event->isInterested(Auth::id()),
                'is_expired' => \Carbon\Carbon::parse($this->event->end_date)->isPast(),
                'is_going_on' => \Carbon\Carbon::parse($this->event->start_date)->isToday() || (\Carbon\Carbon::parse($this->event->start_date)->isPast() && \Carbon\Carbon::parse($this->event->end_date)->isFuture()),
            ] : null,

            // Product details for product posts
            'product_details' => $this->post_type === 'product' && $this->product ? [
                'id' => $this->product->id,
                'name' => $this->product->name,
                'description' => $this->product->description,
                'price' => (float) $this->product->price,
                'currency' => $this->product->currency,
                'location' => $this->product->location,
                'store' => $this->product->store ? [
                    'id' => $this->product->store->id,
                    'name' => $this->product->store->name,
                ] : null,
                'category' => $this->product->category ? [
                    'id' => $this->product->category->id,
                    'name' => $this->product->category->name,
                ] : null,
                'first_media_url' => ($this->product->media && $this->product->media->count() > 0) ? asset('storage/' . $this->product->media->first()->file_path) : null,
            ] : null,

            // Privacy settings
            'settings' => [
                'comments_enabled' => (bool)$this->comments_enabled,
                'privacy_level' => $this->privacy_level,
            ],

            // Emotional context
            'feeling' => [
                'category' => $this->feeling_category ?? '',
                'description' => $this->feeling_description ?? '',
                'type' => $this->feeling_type ?? '',
            ],

            // Technical metadata (non-sensitive)
            'technical' => [
                'category' => $this->post_category ?? '',
                'is_edited' => $this->created_at->ne($this->updated_at),
            ],
            'is_saved' => !empty(DB::table('posts_saved')->where(['post_id' => $this->id, 'user_id' => Auth::id()])->first()) ? 1 : 0,

            // Timestamps
            'dates' => [
                'created' => $this->created_at ? $this->created_at->toISOString() : null,
                'updated' => $this->updated_at ? $this->updated_at->toISOString() : null,
            ],
        ];
    }

    /**
     * Format the media data.
     */
    private function formatMedia($media)
    {

        return $media->map(function ($media) {
            $mediaType = '';
            if (!empty($media->image_or_video)) {
                $mediaType = $this->getMediaType((int) $media->image_or_video);
            } else {
                $mediaType = 'unknown';
            }
            $mediaArr =  [
                'url' => getMedia($media->media_path, $mediaType),
                'thumbnail' => $media->video_thumbnail_url ?? '',
                'original_name' => $media->original_name ?? '',
                'mime_type' => $media->mime_type ?? '',
                'size' => isset($media->file_size) ? (int)$media->file_size : 0,
                'dimensions' => [
                    'width' => $media->media_width ?? 0,
                    'height' => $media->media_height ?? 0,
                ],
            ];
            $mediaArr['type'] = $mediaType;
            return $mediaArr;
        })->toArray();
    }

    /**
     * Get the type of media.
     */
    private function getMediaType(int $type): string
    {
        return match ($type) {
            1 => 'image',
            2 => 'video',
            3 => 'audio',
            4 => 'file',
            default => 'unknown',
        };
    }
}
