<?php

namespace App\Modules\Twilio\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Twilio\Rest\Client as TwilioClient;
use Exception;

/**
 * Twilio Auth Controller
 * 
 * Handles Twilio authentication and credential testing
 */
class TwilioAuthController extends Controller
{
    /**
     * Test Twilio credentials
     */
    public function testCredentials(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'twilio_sid' => 'required|string',
                'twilio_token' => 'required|string',
                'twilio_from' => 'required|string'
            ]);
            
            $accountSid = $request->get('twilio_sid');
            $authToken = $request->get('twilio_token');
            $fromNumber = $request->get('twilio_from');
            
            // Test credentials by creating client and fetching account info
            try {
                $twilioClient = new TwilioClient($accountSid, $authToken);
                $account = $twilioClient->api->accounts($accountSid)->fetch();
                
                if (empty($account->sid)) {
                    return response()->json([
                        'success' => true,
                        'valid' => false,
                        'error' => 'Invalid credentials - account not found'
                    ]);
                }
                
                // Verify from number belongs to this account
                try {
                    $incomingPhoneNumbers = $twilioClient->incomingPhoneNumbers->read(['phoneNumber' => $fromNumber]);
                    if (empty($incomingPhoneNumbers)) {
                        return response()->json([
                            'success' => true,
                            'valid' => false,
                            'error' => 'From number not found in your Twilio account'
                        ]);
                    }
                } catch (\Twilio\Exceptions\RestException $e) {
                    return response()->json([
                        'success' => true,
                        'valid' => false,
                        'error' => 'From number validation failed: ' . $e->getMessage()
                    ]);
                }
                
                return response()->json([
                    'success' => true,
                    'valid' => true,
                    'account_info' => [
                        'account_sid' => $account->sid,
                        'friendly_name' => $account->friendlyName,
                        'status' => $account->status,
                        'type' => $account->type,
                        'from_number' => $fromNumber
                    ]
                ]);
                
            } catch (\Twilio\Exceptions\RestException $e) {
                $errorCode = $e->getCode();
                $errorMessage = $e->getMessage();
                
                if ($errorCode === 401) {
                    $errorMessage = 'Authentication failed: Invalid Account SID or Auth Token';
                } elseif ($errorCode === 404) {
                    $errorMessage = 'Account not found: Invalid Account SID';
                }
                
                Log::error('[TWILIO] Credential test failed', [
                    'error' => $errorMessage,
                    'code' => $errorCode
                ]);
                
                return response()->json([
                    'success' => true,
                    'valid' => false,
                    'error' => $errorMessage
                ]);
            }
            
        } catch (Exception $e) {
            Log::error('Twilio Auth Error - testCredentials: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'error' => 'Failed to test credentials',
                'message' => $e->getMessage()
            ], 500);
        }
    }
}