<?php
namespace App\Http\Controllers\Admin\Sms;

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

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

    public function create()
    {
        $templates = $this->templateService->activeForSend(200);
        return view('admin.sms.send', [
            'templates' => $templates,
        ]);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'from_number'    => ['required','string','max:30'],
            'send_mode'      => ['required','in:one,many,template'], // template == CSV 업로드
            'message'        => ['required','string','max:2000'],
            'sms_type_hint'  => ['nullable','in:auto,sms,mms'],

            'schedule_type'  => ['required','in:now,schedule'],
            'scheduled_at'   => ['nullable','date_format:Y-m-d H:i'],

            'to_number'      => ['nullable','string','max:500'],
            'to_numbers_text'=> ['nullable','string','max:500000'],
            'template_csv'   => ['nullable','file','mimes:csv,txt','max:5120'],
        ]);

        $adminId = (int) auth('admin')->id();
        $res = $this->service->createBatch($adminId, $data, $request);

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

        return redirect()->route('admin.sms.logs.show', ['batchId' => $res['batch_id']])
            ->with('toast', [
                'type' => 'success',
                'title' => '접수 완료',
                'message' => "총 {$res['total']}건 중 유효 {$res['valid']}건을 등록했습니다."
            ]);
    }
}
