<?php

namespace App\Http\Controllers;

use App\Services\N8nOffice;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Request;
use RuntimeException;

class VirtualOfficeController extends Controller
{
    public function workState(N8nOffice $office, string $employee)
    {
        try {
            $state = $office->workState($employee);
        } catch (\Symfony\Component\HttpKernel\Exception\HttpException $exception) {
            throw $exception;
        } catch (ConnectionException $exception) {
            return response()->json(['message' => 'Koneksi status n8n gagal.'], 502);
        } catch (RuntimeException $exception) {
            return response()->json(['message' => $exception->getMessage()], 502);
        }
        return response()->json($state)->header('Cache-Control', 'no-store');
    }

    public function logs(Request $request, N8nOffice $office, string $employee)
    {
        $validated = $request->validate(['cursor' => 'nullable|string|max:2048']);
        try {
            $result = $office->executions($employee, $validated['cursor'] ?? null);
        } catch (\Symfony\Component\HttpKernel\Exception\HttpException $exception) {
            throw $exception;
        } catch (ConnectionException $exception) {
            return response()->json(['message' => 'Koneksi ke n8n gagal atau terlalu lama. Silakan coba lagi.'], 502);
        } catch (RuntimeException $exception) {
            return response()->json(['message' => $exception->getMessage()], 502);
        }

        return response()->json($result)->header('Cache-Control', 'no-store');
    }

    public function executionError(N8nOffice $office, string $employee, string $execution)
    {
        try {
            $result = $office->executionError($employee, $execution);
        } catch (\Symfony\Component\HttpKernel\Exception\HttpException $exception) {
            throw $exception;
        } catch (ConnectionException $exception) {
            return response()->json(['message' => 'Koneksi ke n8n gagal. Silakan coba lagi.'], 502);
        } catch (RuntimeException $exception) {
            return response()->json(['message' => $exception->getMessage()], 502);
        }
        return response()->json($result)->header('Cache-Control', 'no-store');
    }

    public function index(Request $request, N8nOffice $office)
    {
        $filters = $request->validate([
            'q' => 'nullable|string|max:100',
            'status' => 'nullable|in:active,inactive',
        ]);
        $query = trim($filters['q'] ?? '');
        $status = $filters['status'] ?? '';
        $error = null;
        $employees = collect();
        try {
            $employees = $office->employees();
        } catch (ConnectionException $exception) {
            $error = 'Koneksi ke n8n gagal atau terlalu lama. Silakan coba lagi.';
        } catch (RuntimeException $exception) {
            $error = $exception->getMessage();
        }
        $total = $employees->count();
        $active = $employees->where('active', true)->count();
        $employees = $employees->filter(fn ($employee) =>
            ($query === '' || mb_stripos($employee['name'].' '.implode(' ', $employee['tags']), $query) !== false)
            && ($status === '' || $employee['active'] === ($status === 'active'))
        );

        return view('virtual-office.index', compact('employees', 'total', 'active', 'query', 'status', 'error'));
    }
}
