<?php

namespace App\Http\Controllers\Admin;

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

class TaskBoardController extends Controller
{
    public function __construct(protected DailyWorkflowService $workflow)
    {
    }

    public function index(Request $request): View
    {
        $filters = $request->only(['q', 'client_id', 'priority', 'status', 'category', 'assigned_to', 'due']);
        $data = $this->workflow->board($filters);

        return view('admin.task-board.index', compact('data', 'filters'));
    }

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

        $validated = $request->validate([
            'client_id' => ['nullable', 'exists:clients,id'],
            'title' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string'],
            'category' => ['nullable', 'string', 'max:60'],
            'priority' => ['required', 'in:critical,high,medium,low'],
            'status' => ['nullable', 'in:open,in_progress,waiting,completed,cancelled'],
            'assigned_to' => ['nullable', 'exists:users,id'],
            'due_at' => ['nullable', 'date'],
        ]);

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

        return back()->with('success', 'Görev oluşturuldu.');
    }

    public function update(Request $request, OperationTask $task): RedirectResponse
    {
        $validated = $request->validate([
            'title' => ['sometimes', 'required', 'string', 'max:255'],
            'description' => ['nullable', 'string'],
            'category' => ['nullable', 'string', 'max:60'],
            'priority' => ['sometimes', 'required', 'in:critical,high,medium,low'],
            'status' => ['sometimes', 'required', 'in:open,in_progress,waiting,completed,cancelled'],
            'assigned_to' => ['nullable', 'exists:users,id'],
            'due_at' => ['nullable', 'date'],
        ]);

        if (array_key_exists('status', $validated)) {
            $validated['completed_at'] = $validated['status'] === 'completed' ? now() : null;
        }

        $task->update($validated);

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

    public function complete(OperationTask $task): RedirectResponse
    {
        $task->update([
            'status' => 'completed',
            'completed_at' => now(),
        ]);

        return back()->with('success', 'Görev tamamlandı.');
    }

    public function destroy(OperationTask $task): RedirectResponse
    {
        $task->delete();

        return back()->with('success', 'Görev silindi.');
    }

    public function generate(Request $request): RedirectResponse
    {
        $result = $this->workflow->generateDailyTasks($request->only(['readiness', 'platform']));

        return back()->with('success', $result['message']);
    }
}
