<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\PaymentProfile;
use Illuminate\Support\Facades\Log;
use App\Traits\UserTraits;

class PaymentProfileController extends Controller
{
    use UserTraits;

    /**
     * Get the authenticated company's payment profile by provider (e.g., 'stripe').
     */
    public function getAccountByProvider(Request $request, string $provider)
    {
        // Validate the provider using Laravel's validator
        $request->merge(['provider' => $provider]);

        $validated = $request->validate([
            'provider' => 'required|in:stripe,ach,paypal',
        ]);

        $user = $this->getCurrentUser();
        $companyId = $user->company_id ?? null;

        if (!$companyId) {
            return response()->json([
                'success' => false,
                'message' => 'Missing company ID for authenticated user.',
            ], 422);
        }

        $profile = PaymentProfile::select([
                'company_id',
                'provider',
                'provider_customer_id',
                'provider_account_id',
            ])
            ->where('company_id', $companyId)
            ->where('provider', $validated['provider'])
            ->first();

        if (!$profile) {
            return response()->json([
                'success' => false,
                'message' => 'Payment profile not found',
            ], 404);
        }

        // Optional: log the successful fetch
        Log::info('Payment profile fetched', [
            'company_id' => $companyId,
            'provider' => $validated['provider'],
        ]);

        return response()->json([
            'success' => true,
            'data' => $profile,
        ]);
    }
}
