<?php
namespace App\Services\Payments;

use App\Models\CompanySubscriptions;
use App\Models\PaymentProfile;

/**
 * Handles creation and validation of PaymentProfile records.
 *
 * Ensures every company has a PaymentProfile once a subscription is created.
 * This avoids duplicate entries and prepares the company for any provider.
 */
class PaymentProfileService
{
    /**
     * Create a PaymentProfile if one doesn't already exist for the company.
     *
     * Conditions:
     * - Only creates if `company_id` and `customer_id` are set.
     * - Checks existence by `company_id` only (provider not required).
     * - `provider_account_id` and `metadata` are left empty.
     *
     * @param CompanySubscriptions $subscription
     */
    public function createIfNotExistsFromSubscription(CompanySubscriptions $subscription): void
    {
        if (!$subscription->customer_id || !$subscription->company_id) {
            return;
        }

        $alreadyExists = PaymentProfile::where('company_id', $subscription->company_id)
            ->exists();

        if (!$alreadyExists) {
            PaymentProfile::create([
                'company_id' => $subscription->company_id,
                'provider' => 'stripe', // or leave dynamic if needed later
                'provider_customer_id' => $subscription->customer_id,
                // provider_account_id and metadata intentionally not set
            ]);
        }
    }
}
