<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Client;
use App\Models\OperationTask;
use App\Services\Operations\OperationCenterService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Illuminate\View\View;

class OperationsController extends Controller
{
    public function __construct(protected OperationCenterService $operations)
    {
    }

    public function index(Request $request): View
    {
        $filters = $request->only(['q', 'platform', 'status', 'readiness']);
        $data = $this->operations->dashboard($filters);

        return view('admin.operations.index', compact('data', 'filters'));
    }

    public function show(Client $client): View
    {
        $data = $this->operations->clientDetail($client);

        return view('admin.operations.show', compact('data', 'client'));
    }

    public function storeTask(Request $request, Client $client): RedirectResponse
    {
        if (! Schema::hasTable('operation_tasks')) {
            return back()->with('error', 'Operasyon görevleri tablosu bulunamadı. Migration çalıştırılmalı.');
        }

        $validated = $request->validate([
            'title' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string'],
            'category' => ['nullable', 'string', 'max:60'],
            'priority' => ['required', 'in:critical,high,medium,low'],
            'due_at' => ['nullable', 'date'],
        ]);

        OperationTask::create([
            'client_id' => $client->id,
            'title' => $validated['title'],
            'description' => $validated['description'] ?? null,
            'category' => $validated['category'] ?? 'general',
            'priority' => $validated['priority'],
            'status' => 'open',
            'due_at' => $validated['due_at'] ?? null,
            'created_by' => auth()->id(),
        ]);

        return back()->with('success', 'Operasyon görevi eklendi.');
    }

    public function updateTask(Request $request, OperationTask $task): RedirectResponse
    {
        $validated = $request->validate([
            'status' => ['required', 'in:open,in_progress,waiting,completed,cancelled'],
        ]);

        $task->update([
            'status' => $validated['status'],
            'completed_at' => $validated['status'] === 'completed' ? now() : null,
        ]);

        return back()->with('success', 'Operasyon görevi güncellendi.');
    }
}
