<?php

namespace App\Services\Client;

use App\Models\MemberUser;
use App\Models\MemberSocialAccount;
use App\Models\SysConfig;
use App\Models\Wallet;
use App\Models\CoachUser;
use App\Models\WalletWithdrawRecord;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;


class AccountService
{
    /**
     * 发送验证码
     */
    public function sendVerifyCode(string $mobile)
    {
        // 生成验证码
        $code = mt_rand(100000, 999999);
        
        // 保存验证码到缓存
        Cache::put("verify_code:{$mobile}", $code, 300);
        
        // TODO: 调用短信服务发送验证码
        
        return ['code' => $code];
    }

    /**
     * 用户登录
     */
    public function login(string $mobile, string $code)
    {

        // 验证验证码
        $cacheCode = Cache::get("verify_code:{$mobile}");

        if (!$cacheCode || $cacheCode != $code) {
            throw new \Exception('验证码错误');
        }
       
        // 查找或创建用户
        $user = MemberUser::firstOrCreate(
            ['mobile' => $mobile],
            [
                'state' => 'enable',
                'register_area' => request()->header('area_code')
            ]
        );

        // 生成token
        $token = $user->createToken('auth-token')->plainTextToken;

        return [
            'token' => $token,
            'user' => $user
        ];
    }

    /**
     * 微信登录
     */
    public function wxLogin(string $openid)
    {
        // 查找或创建微信用户
        $socialAccount = MemberSocialAccount::firstOrCreate(
            [
                'platform' => 'WECHAT',
                'social_id' => $openid
            ]
        );

        $user = $socialAccount->user;
        if (!$user) {
            $user = MemberUser::create([
                'state' => 'enable',
                'register_area' => request()->header('area_code')
            ]);
            $socialAccount->update(['user_id' => $user->id]);
        }

        // 生成token
        $token = $user->createToken('auth-token')->plainTextToken;

        return [
            'token' => $token,
            'user' => $user
        ];
    }

    /**
     * 用户退出
     */
    public function logout()
    {
        Auth::user()->tokens()->delete();
        return ['message' => '退出成功'];
    }

    /**
     * 用户注销
     */
    public function deleteAccount()
    {
        $user = Auth::user();
      
        if (!$user || $user->state !== 'enable') {
            throw new \Exception('用户状态异常');
        }

        $user->state = 'disable';
        $user->save();
        $user->delete();
        $user->tokens()->delete();
        return ['message' => '账号已注销'];
    }

} 