<?php

namespace App\Services;

use App\Enums\UserRole;
use App\Models\Business;
use App\Models\Plan;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class BusinessOnboardingService
{
    public function create(array $data): User
    {
        return DB::transaction(function () use ($data): User {
            $business = Business::create([
                'name' => $data['business_name'],
                'slug' => Str::slug($data['business_name']).'-'.Str::lower(Str::random(6)),
                'email' => $data['email'],
            ]);

            $user = User::create([
                'business_id' => $business->id,
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => $data['password'],
                'role' => UserRole::Owner,
            ]);

            $plan = Plan::firstOrCreate(
                ['slug' => 'professional'],
                ['name' => 'Professional', 'price_kobo' => 0, 'member_limit' => 500, 'staff_limit' => 15, 'features' => ['reports', 'notifications', 'api']]
            );

            $business->subscriptions()->create([
                'plan_id' => $plan->id,
                'status' => 'trialing',
                'trial_ends_at' => now()->addDays(14),
                'ends_at' => now()->addDays(14),
            ]);

            return $user;
        });
    }
}
