<?php

namespace App\Http\Controllers\Admin;

use App\Services\Admin\AdminMeService;
use Illuminate\Http\Request;
use App\Repositories\Admin\AdminUserRepository;

final class MeController
{
    public function __construct(
        private readonly AdminMeService $service
    ) {}

    public function show(Request $request)
    {
        $me = $request->user('admin');

        $phonePlain = $this->service->decryptPhoneForMe($me);

        $repo = app(AdminUserRepository::class);
        $roles = $repo->getRolesForUser((int)$me->id);
        $perms = $repo->getPermissionsForUser((int)$me->id);

        return view('admin.me.show', [
            'me' => $me,
            'phone_plain' => $phonePlain,
            'roles' => $roles,
            'perms' => $perms,
        ]);
    }

    public function update(Request $request)
    {
        $me = $request->user('admin');

        $res = $this->service->updateProfile($me->id, $request);

        if (!($res['ok'] ?? false)) {
            return redirect()
                ->back()
                ->withInput()
                ->with('toast', [
                    'type' => 'danger',
                    'title' => '저장 실패',
                    'message' => $res['message'] ?? '수정에 실패했습니다.',
                ]);
        }

        // ✅ 핵심: 성공도 view() 말고 redirect
        return redirect()
            ->route('admin.me')
            ->with('toast', [
                'type' => 'success',
                'title' => '저장 완료',
                'message' => '변경되었습니다.',
            ]);
    }

    public function showPassword()
    {
        return view('admin.me.password');
    }

    public function updatePassword(Request $request)
    {
        $me = $request->user('admin');

        $res = $this->service->changePassword($me->id, $request);

        if (!($res['ok'] ?? false)) {
            return redirect()
                ->back()
                ->withInput()
                ->with('toast', [
                    'type' => 'danger',
                    'title' => '저장 실패',
                    'message' => $res['message'] ?? '수정에 실패했습니다.',
                ]);
        }

        // ✅ 핵심: 성공도 view() 말고 redirect
        return redirect()
            ->route('admin.me')
            ->with('toast', [
                'type' => 'success',
                'title' => '저장 완료',
                'message' => '변경되었습니다.',
            ]);
    }
}
