<?php

namespace App\Services\Providers;

use App\Models\ScheduledReel;
use App\Models\SocialAccount;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class InstagramProvider implements ReelProviderInterface
{
    /**
     * Post a reel to Instagram.
     *
     * @param ScheduledReel $reel
     * @param SocialAccount $account
     * @return array
     */
    public function postReel(ScheduledReel $reel, SocialAccount $account): array
    {
        try {
            // Check if account has valid token
            $token = $account->getDecryptedToken();
            
            if (!$token) {
                return [
                    'status' => 'failed',
                    'message' => 'Missing access token'
                ];
            }
            
            // Check if token is expired
            if ($account->isTokenExpired()) {
                // Try to refresh token if refresh token exists
                if ($refreshToken = $account->getRefreshToken()) {
                    $refreshed = $this->refreshToken($account, $refreshToken);
                    if ($refreshed) {
                        $token = $account->getDecryptedToken();
                    } else {
                        return [
                            'status' => 'failed',
                            'message' => 'Token expired and refresh failed'
                        ];
                    }
                } else {
                    return [
                        'status' => 'failed',
                        'message' => 'Token expired and no refresh token available'
                    ];
                }
            }
            
            // Get signed source URLs
            $sourceUrls = $reel->getSignedSourceUrls();
            
            if (empty($sourceUrls)) {
                return [
                    'status' => 'failed',
                    'message' => 'No source media found'
                ];
            }
            
            // For demo accounts, just return success
            if ($account->isDemo()) {
                return [
                    'status' => 'success',
                    'message' => 'Reel posted successfully (demo)',
                    'post_id' => 'demo_' . time(),
                    'permalink' => 'https://instagram.com/demo/reel_' . time()
                ];
            }
            
            // In a real implementation, you would:
            // 1. Download the source media
            // 2. Process it according to the template and options
            // 3. Upload it to Instagram
            
            // For now, we'll simulate a successful post
            Log::info('Posting reel to Instagram', [
                'scheduled_reel_id' => $reel->id,
                'social_account_id' => $account->id,
                'source_count' => count($sourceUrls)
            ]);
            
            return [
                'status' => 'success',
                'message' => 'Reel posted successfully',
                'post_id' => 'post_' . time(),
                'permalink' => 'https://instagram.com/reel/post_' . time()
            ];
        } catch (\Exception $e) {
            Log::error('Failed to post reel to Instagram: ' . $e->getMessage(), [
                'scheduled_reel_id' => $reel->id,
                'social_account_id' => $account->id,
                'trace' => $e->getTraceAsString()
            ]);
            
            return [
                'status' => 'failed',
                'message' => $e->getMessage()
            ];
        }
    }
    
    /**
     * Refresh Instagram access token.
     *
     * @param SocialAccount $account
     * @param string $refreshToken
     * @return bool
     */
    protected function refreshToken(SocialAccount $account, string $refreshToken): bool
    {
        try {
            $response = Http::asForm()->post('https://graph.instagram.com/refresh_access_token', [
                'grant_type' => 'ig_refresh_token',
                'access_token' => $refreshToken
            ]);
            
            if ($response->successful()) {
                $data = $response->json();
                
                $account->update([
                    'access_token_encrypted' => \Crypt::encryptString($data['access_token']),
                    'token_expires_at' => now()->addSeconds($data['expires_in'] ?? 5184000) // Default to 60 days
                ]);
                
                return true;
            }
            
            return false;
        } catch (\Exception $e) {
            Log::error('Failed to refresh Instagram token: ' . $e->getMessage(), [
                'social_account_id' => $account->id,
                'trace' => $e->getTraceAsString()
            ]);
            
            return false;
        }
    }
}