<?php

namespace App\Services;

use App\Models\{Business,Package,Subscription,User};
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

class SubscriptionService
{
    /** নতুন ব্যবসা + সাবস্ক্রিপশন অটো-ক্রিয়েট */
    public function provision(User $owner, Package $package, array $businessData): Business
    {
        return DB::transaction(function () use ($owner, $package, $businessData) {
            // unique subdomain if not given
            $sub = $businessData['subdomain'] ?? Str::slug($businessData['name']).'-'.Str::lower(Str::random(4));

            $biz = Business::create([
                'name'      => $businessData['name'],
                'owner_id'  => $owner->id,
                'subdomain' => $sub,
                'timezone'  => $businessData['timezone'] ?? 'Asia/Dhaka',
                'is_active' => true,
            ]);

            // attach owner as owner role
            $biz->users()->attach($owner->id, ['role' => 'owner']);

            // subscription window
            $start = now()->startOfDay();
            $end   = (clone $start)->addMonths(max(1, (int)$package->duration_months))->subDay(); // inclusive end

            Subscription::create([
                'business_id' => $biz->id,
                'package_id'  => $package->id,
                'starts_at'   => $start,
                'ends_at'     => $end,
                'auto_renew'  => false,
                'status'      => 'active',
            ]);

            // (Optional) প্রভিশনিং টাস্ক: ডিফল্ট ওয়্যারহাউস/সেটিংস/রোল ইত্যাদি
            // ...

            return $biz;
        });
    }
}