<?php

namespace App\Http\Controllers\Admin\Members;

use App\Services\Admin\Member\AdminMemberService;
use Illuminate\Http\Request;

final class AdminMembersController
{
    public function __construct(
        private readonly AdminMemberService $service,
    ) {}

    public function index(Request $request)
    {
        $data = $this->service->list($request->all());
        return view('admin.members.index', $data);
    }

    public function show(int $memNo, Request $request)
    {
        $data = $this->service->showData($memNo);

        if (!($data['member'] ?? null)) {
            return redirect()->route('admin.members.index')->with('toast', [
                'type' => 'danger',
                'title' => '조회 실패',
                'message' => '회원을 찾을 수 없습니다.',
            ]);
        }

        return view('admin.members.show', $data);
    }

    public function update(int $memNo, Request $request)
    {
        $actorId = (int) auth('admin')->id();

        $res = $this->service->updateMember(
            memNo: $memNo,
            input: $request->all(),
            actorAdminId: $actorId,
            ip: (string) $request->ip(),
            ua: (string) ($request->userAgent() ?? ''),
        );

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

        return redirect()
            ->route('admin.members.show', ['memNo' => $memNo])
            ->with('toast', [
                'type' => 'success',
                'title' => '저장 완료',
                'message' => $res['message'] ?? '변경되었습니다.',
            ]);
    }

    public function addMemo(int $memNo, Request $request)
    {
        $data = $request->validate([
            'memo' => ['required', 'string', 'max:1000'],
        ]);

        $res = $this->service->addMemo(
            memNo: $memNo,
            memo: trim((string) $data['memo']),
            actorAdminId: (int) auth('admin')->id(),
            ip: (string) $request->ip(),
            ua: (string) ($request->userAgent() ?? ''),
        );

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

        return redirect()
            ->route('admin.members.show', ['memNo' => $memNo])
            ->with('toast', [
                'type' => 'success',
                'title' => '메모 등록',
                'message' => '메모가 추가되었습니다.',
            ]);
    }

    public function resetPassword(int $memNo, Request $request)
    {
        // 옵션: mode=random|email (기본 random)
        $data = $request->validate([
            'mode' => ['nullable', 'string', 'in:random,email'],
        ]);

        $res = $this->service->resetPassword(
            memNo: $memNo,
            mode: (string)($data['mode'] ?? 'random'),
            actorAdminId: (int) auth('admin')->id(),
            ip: (string) $request->ip(),
            ua: (string) ($request->userAgent() ?? ''),
        );

        if (!($res['ok'] ?? false)) {
            return redirect()->back()->with('toast', [
                'type' => 'danger',
                'title' => '초기화 실패',
                'message' => $res['message'] ?? '비밀번호 초기화에 실패했습니다.',
            ]);
        }

        return redirect()
            ->route('admin.members.show', ['memNo' => $memNo])
            ->with('toast', [
                'type' => 'success',
                'title' => '비밀번호 초기화',
                'message' => $res['message'] ?? '임시 비밀번호가 발급되었습니다.',
            ]);
    }

    public function forceOut(int $memNo, Request $request)
    {
        $res = $this->service->forceOut(
            memNo: $memNo,
            actorAdminId: (int) auth('admin')->id(),
            ip: (string) $request->ip(),
            ua: (string) ($request->userAgent() ?? ''),
        );

        if (!($res['ok'] ?? false)) {
            return redirect()->back()->with('toast', [
                'type' => 'danger',
                'title' => '강제탈퇴 실패',
                'message' => $res['message'] ?? '강제탈퇴 처리에 실패했습니다.',
            ]);
        }

        return redirect()
            ->route('admin.members.show', ['memNo' => $memNo])
            ->with('toast', [
                'type' => 'success',
                'title' => '강제탈퇴 처리',
                'message' => $res['message'] ?? '강제탈퇴 및 비식별 처리가 완료되었습니다.',
            ]);
    }
}
