<?php

namespace App\Http\Controllers\Admin\Sms;

use App\Http\Controllers\Controller;
use App\Services\Admin\Sms\AdminSmsTemplateService;
use Illuminate\Http\Request;

final class AdminSmsTemplateController extends Controller
{
    public function __construct(
        private readonly AdminSmsTemplateService $service,
    ) {}

    /**
     * GET admin.templates.index
     */
    public function index(Request $request)
    {
        $filters = $request->only(['active', 'q']);
        $templates = $this->service->list($filters, 30);

        return view('admin.templates.index', [
            'templates' => $templates,
        ]);
    }

    /**
     * GET admin.templates.create
     */
    public function create()
    {
        return view('admin.templates.form', [
            'mode' => 'create',
            'tpl'  => (object)[
                'id' => null,
                'code' => '',
                'title' => '',
                'body' => '',
                'description' => '',
                'is_active' => 1,
            ],
        ]);
    }

    /**
     * POST admin.templates.store
     */
    public function store(Request $request)
    {
        $data = $request->validate([
            'code'        => ['required', 'string', 'max:60', 'regex:/^[a-zA-Z0-9\-_]{3,60}$/'],
            'title'       => ['required', 'string', 'max:120'],
            'body'        => ['required', 'string', 'max:5000'],
            'description' => ['nullable', 'string', 'max:255'],
            // checkbox는 존재 여부로 처리
        ]);

        $adminId = (int) auth('admin')->id();

        $res = $this->service->create($adminId, [
            'code'        => $data['code'],
            'title'       => $data['title'],
            'body'        => $data['body'],
            'description' => $data['description'] ?? null,
            'is_active'   => $request->has('is_active') ? 1 : 0,
        ]);

        if (!$res['ok']) {
            return back()->withInput()->with('toast', [
                'type' => 'danger',
                'title' => '실패',
                'message' => $res['message'] ?? '템플릿 생성에 실패했습니다.',
            ]);
        }

        return redirect()->route('admin.templates.edit', ['id' => $res['id']])->with('toast', [
            'type' => 'success',
            'title' => '완료',
            'message' => '템플릿이 생성되었습니다.',
        ]);
    }

    /**
     * GET admin.templates.edit
     */
    public function edit(int $id)
    {
        $tpl = $this->service->get($id);
        if (!$tpl) {
            return redirect()->route('admin.templates.index')->with('toast', [
                'type' => 'danger',
                'title' => '없음',
                'message' => '템플릿을 찾을 수 없습니다.',
            ]);
        }

        return view('admin.templates.form', [
            'mode' => 'edit',
            'tpl'  => $tpl,
        ]);
    }

    /**
     * PUT admin.templates.update
     */
    public function update(int $id, Request $request)
    {
        $tpl = $this->service->get($id);
        if (!$tpl) {
            return redirect()->route('admin.templates.index')->with('toast', [
                'type' => 'danger',
                'title' => '없음',
                'message' => '템플릿을 찾을 수 없습니다.',
            ]);
        }

        $data = $request->validate([
            'title'       => ['required', 'string', 'max:120'],
            'body'        => ['required', 'string', 'max:5000'],
            'description' => ['nullable', 'string', 'max:255'],
        ]);

        $res = $this->service->update($id, [
            'title'       => $data['title'],
            'body'        => $data['body'],
            'description' => $data['description'] ?? null,
            'is_active'   => $request->has('is_active') ? 1 : 0,
        ]);

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

        return redirect()->route('admin.templates.edit', ['id' => $id])->with('toast', [
            'type' => 'success',
            'title' => '완료',
            'message' => '저장되었습니다.',
        ]);
    }
}
