<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\OauthAccount;
use App\Models\Merchant;
use App\Models\User;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function login(Request $request): JsonResponse
    {
        $data = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required', 'string'],
            'source' => ['nullable', 'string'],
        ]);

        $user = User::query()->where('email', $data['email'])->first();
        if (! $user || ! Hash::check($data['password'], $user->password)) {
            return ApiResponse::error('账号或密码错误', 1001, null, 422);
        }

        $source = $data['source'] ?? 'pc';
        $user->forceFill(['last_login_source' => $source])->save();

        return ApiResponse::success([
            'token' => base64_encode($user->id . '|' . now()->timestamp . '|demo'),
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'source' => $source,
            ],
        ], '登录成功');
    }

    public function wechatPlaceholder(Request $request): JsonResponse
    {
        $data = $request->validate([
            'platform' => ['required', 'in:wechat_mp,wechat_mini,app'],
            'openid' => ['nullable', 'string'],
            'unionid' => ['nullable', 'string'],
            'nickname' => ['nullable', 'string'],
        ]);

        $merchant = Merchant::query()->first();
        $user = User::query()->first();

        if ($user && ($data['openid'] ?? null)) {
            OauthAccount::query()->updateOrCreate(
                [
                    'provider' => $data['platform'],
                    'openid' => $data['openid'],
                ],
                [
                    'user_id' => $user->id,
                    'merchant_id' => $merchant?->id,
                    'platform' => $data['platform'],
                    'provider' => $data['platform'],
                    'unionid' => $data['unionid'] ?? null,
                    'nickname' => $data['nickname'] ?? null,
                    'raw_payload' => $data,
                ]
            );
        }

        return ApiResponse::success([
            'platform' => $data['platform'],
            'next_step' => '待接入真实微信 / App 登录流程',
            'received' => $data,
        ], '渠道登录占位已预留');
    }
}
