<?php

namespace App\Jobs;

use App\Models\Post;
use App\Models\ActivityLog;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class PublishPostJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public Post $post;

    public function __construct(Post $post)
    {
        $this->post = $post;
    }

    public function handle(): void
    {
        $post = Post::with('platforms')->find($this->post->id);

        if (!$post) {
            Log::warning("PublishPostJob: Post not found", ['post_id' => $this->post->id]);
            return;
        }

        $results = [];
        $allSuccess = true;

        foreach ($post->platforms as $account) {
            try {
                $result = $this->publishToPlatform($post, $account);
                $results[] = $result;

                $post->postPlatforms()
                    ->where('social_account_id', $account->id)
                    ->update([
                        'publish_status' => 'published',
                        'publish_response' => json_encode($result),
                        'published_at' => now(),
                    ]);
            } catch (\Exception $e) {
                $allSuccess = false;
                $results[] = [
                    'platform' => $account->platform_name,
                    'success' => false,
                    'error' => $e->getMessage(),
                ];

                $post->postPlatforms()
                    ->where('social_account_id', $account->id)
                    ->update([
                        'publish_status' => 'failed',
                        'publish_response' => json_encode(['error' => $e->getMessage()]),
                    ]);

                Log::error("PublishPostJob failed for platform", [
                    'post_id' => $post->id,
                    'platform' => $account->platform_name,
                    'error' => $e->getMessage(),
                ]);
            }
        }

        $finalStatus = $allSuccess ? 'published' : 'failed';

        $post->update([
            'status' => $finalStatus,
            'published_at' => $finalStatus === 'published' ? now() : $post->published_at,
            'publish_log' => json_encode([
                'published_at' => now()->toDateTimeString(),
                'results' => $results,
            ]),
        ]);

        ActivityLog::create([
            'user_id' => $post->user_id,
            'action' => 'post_published',
            'model_type' => Post::class,
            'model_id' => $post->id,
            'description' => "Post published with status: {$finalStatus}",
            'metadata' => ['results' => $results],
        ]);
    }

    private function publishToPlatform(Post $post, $account): array
    {
        $platform = $account->platform_name;
        $content = $post->content;
        $mediaUrl = $post->media_url;

        // Simulated API calls - no real API keys required
        $simulatedResponses = [
            'facebook' => [
                'id' => 'fb_' . uniqid(),
                'url' => 'https://facebook.com/posts/' . uniqid(),
                'message' => 'Posted to Facebook successfully',
            ],
            'instagram' => [
                'id' => 'ig_' . uniqid(),
                'url' => 'https://instagram.com/p/' . uniqid(),
                'message' => 'Posted to Instagram successfully',
            ],
            'twitter' => [
                'id' => 'tw_' . uniqid(),
                'url' => 'https://twitter.com/status/' . uniqid(),
                'message' => 'Posted to X (Twitter) successfully',
            ],
            'linkedin' => [
                'id' => 'li_' . uniqid(),
                'url' => 'https://linkedin.com/posts/' . uniqid(),
                'message' => 'Posted to LinkedIn successfully',
            ],
        ];

        // Simulate network delay
        usleep(100000); // 100ms

        $response = $simulatedResponses[$platform] ?? [
            'id' => 'unknown_' . uniqid(),
            'message' => 'Posted successfully',
        ];

        Log::info("Simulated publish to {$platform}", [
            'post_id' => $post->id,
            'account' => $account->account_name,
            'response' => $response,
        ]);

        return [
            'platform' => $platform,
            'success' => true,
            'response' => $response,
            'account_name' => $account->account_name,
            'published_at' => now()->toDateTimeString(),
        ];
    }

    public function failed(\Throwable $exception): void
    {
        Log::error("PublishPostJob failed completely", [
            'post_id' => $this->post->id,
            'error' => $exception->getMessage(),
        ]);

        $this->post->update([
            'status' => 'failed',
            'publish_log' => json_encode([
                'error' => $exception->getMessage(),
                'failed_at' => now()->toDateTimeString(),
            ]),
        ]);
    }
}
