<?php

namespace App\Console\Commands;

use App\Models\SocialPost;
use Illuminate\Console\Command;

class BackfillPlatformPostIds extends Command
{
    protected $signature = 'posts:backfill-ids';
    protected $description = 'Backfill platform_post_id from platform_response for existing posts';

    public function handle()
    {
        $this->info('Starting backfill of platform_post_id...');

        $posts = SocialPost::with('account.platform')
            ->whereNotNull('platform_response')
            ->whereNull('platform_post_id')
            ->where('status', 1) // Only successful posts
            ->get();

        $this->info("Found {$posts->count()} posts to process");

        $updated = 0;
        $failed = 0;

        foreach ($posts as $post) {
            $response = $post->platform_response;

            // Handle both JSON string and array
            if (is_string($response)) {
                $response = json_decode($response, true);
            }

            if (!$response || !is_array($response)) {
                $this->warn("Post #{$post->id}: Invalid response format");
                $failed++;
                continue;
            }

            $platform = strtolower($post->account->platform->slug ?? '');
            $platformPostId = $this->extractPlatformPostId($response, $platform);

            if ($platformPostId) {
                $post->platform_post_id = $platformPostId;

                // Also set posted_at if null
                if (!$post->posted_at) {
                    $post->posted_at = $post->updated_at ?? $post->created_at;
                }

                $post->save();

                $this->line("✓ Post #{$post->id} ({$platform}): {$platformPostId}");
                $updated++;
            } else {
                $this->warn("✗ Post #{$post->id} ({$platform}): Could not extract ID from URL: " . ($response['url'] ?? 'N/A'));
                $failed++;
            }
        }

        $this->newLine();
        $this->info("Backfill complete: {$updated} updated, {$failed} failed");

        return Command::SUCCESS;
    }

    protected function extractPlatformPostId(array $response, string $platform): ?string
    {
        if (!empty($response['post_id'])) {
            return (string) $response['post_id'];
        }

        // YouTube returns video_id
        if (!empty($response['video_id'])) {
            return (string) $response['video_id'];
        }

        if (!empty($response['id'])) {
            return (string) $response['id'];
        }

        $url = $response['url'] ?? null;
        if (!$url) {
            return null;
        }

        switch ($platform) {
            case 'twitter':
                if (preg_match('/status\/(\d+)/', $url, $matches)) {
                    return $matches[1];
                }
                break;

            case 'facebook':
                if (preg_match('/posts\/(\d+)/', $url, $matches)) {
                    return $matches[1];
                }
                if (preg_match('/(\d+)$/', $url, $matches)) {
                    return $matches[1];
                }
                break;

            case 'instagram':
                if (preg_match('/\/p\/([A-Za-z0-9_-]+)/', $url, $matches)) {
                    return $matches[1];
                }
                break;

            case 'linkedin':
                if (preg_match('/activity-(\d+)/', $url, $matches)) {
                    return $matches[1];
                }
                if (preg_match('/urn:li:share:(\d+)/', $url, $matches)) {
                    return 'urn:li:share:' . $matches[1];
                }
                break;

            case 'tiktok':
                if (preg_match('/video\/(\d+)/', $url, $matches)) {
                    return $matches[1];
                }
                break;

            case 'youtube':
                if (preg_match('/[?&]v=([^&]+)/', $url, $matches)) {
                    return $matches[1];
                }
                if (preg_match('/youtu\.be\/([^?&]+)/', $url, $matches)) {
                    return $matches[1];
                }
                break;

            case 'threads':
                if (preg_match('/post\/(\d+)/', $url, $matches)) {
                    return $matches[1];
                }
                if (preg_match('/\/(\d+)\/?$/', $url, $matches)) {
                    return $matches[1];
                }
                break;
        }

        return null;
    }
}
