<?php

namespace App\Services;

use App\Mail\WelcomeAccountMail;
use App\Models\Subscription;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;

class AccountService
{
    /**
     * Membuat / mengaktifkan akun user setelah pembayaran sukses.
     *
     * @param  array  $data  [email, name, package_name, price]
     * @param  bool   $withSubscription  buat subscription aktif atau tidak
     * @return array{user: User, password: string|null, is_new: bool}
     */
    public function provision(array $data, bool $withSubscription = true): array
    {
        $existing = User::where('email', $data['email'])->first();

        if ($existing) {
            $user = $existing;
            $plainPassword = null;
        } else {
            $plainPassword = Str::password(10);

            $user = User::create([
                'name' => $data['name'] ?? $data['email'],
                'email' => $data['email'],
                'password' => Hash::make($plainPassword),
                'role' => 'user',
            ]);

            Mail::to($user->email)->queue(new WelcomeAccountMail($user, $plainPassword));
        }

        if ($withSubscription) {
            $existingSub = $user->subscriptions()->latest()->first();

            if ($existingSub && $existingSub->status === 'active' && $existingSub->expires_at && $existingSub->expires_at->isFuture()) {
                // User sudah punya subscription aktif, skip pembuatan baru
            } else {
                Subscription::create([
                    'user_id' => $user->id,
                    'package_name' => $data['package_name'] ?? 'Basic',
                    'price' => $data['price'] ?? 0,
                    'starts_at' => now(),
                    'expires_at' => now()->addMonth(),
                    'status' => 'active',
                ]);
            }
        }

        return [
            'user' => $user,
            'password' => $plainPassword,
            'is_new' => !$existing,
        ];
    }

    /**
     * Buat akun trial baru (user registrasi sendiri).
     */
    public function provisionTrial(array $data): array
    {
        $existing = User::where('email', $data['email'])->first();

        if ($existing) {
            return [
                'user' => $existing,
                'is_new' => false,
            ];
        }

        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'role' => 'user',
        ]);

        Subscription::create([
            'user_id' => $user->id,
            'package_name' => 'Trial',
            'price' => 0,
            'starts_at' => now(),
            'expires_at' => now()->addDays(14),
            'status' => 'trial',
        ]);

        return [
            'user' => $user,
            'is_new' => true,
        ];
    }
}
