<?php

namespace App\Http\Controllers\Frontdesk;

use App\Http\Controllers\Controller;
use App\Models\LabResult;
use App\Models\Order;
use App\Services\ResultWatermarkService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Response;

class ResultController extends Controller
{
    public function __construct(private readonly ResultWatermarkService $watermarkService)
    {
    }

    public function store(Request $request, Order $order): RedirectResponse
    {
        $this->ensureOrderAccessible($request, $order);

        $data = $request->validate([
            'result_file' => ['required', 'file', 'mimes:pdf,jpg,jpeg,png,webp', 'max:20480'],
        ]);

        try {
            $version = (int) $order->results()->max('version') + 1;
            $watermarkText = 'CONFIDENTIAL | '.$order->order_code.' | '.now()->format('Y-m-d');

            $relativePath = $this->watermarkService->storeWatermarked($data['result_file'], $watermarkText);

            $order->results()->create([
                'version' => $version,
                'file_path' => $relativePath,
                'uploaded_by' => $request->user()->id,
                'ready_at' => now(),
            ]);

            if ($order->status !== 'delivered') {
                $order->update([
                    'status' => 'ready',
                    'ready_at' => now(),
                ]);
            }
        } catch (\Throwable $e) {
            Log::error('Result upload failed.', [
                'order_id' => $order->id,
                'user_id' => $request->user()->id,
                'role' => $request->user()->role,
                'message' => $e->getMessage(),
            ]);

            return back()
                ->withInput()
                ->withErrors([
                    'result_file' => 'Result upload failed. Check file format and try again. If it persists, contact admin.',
                ]);
        }

        return back()->with('success', 'Watermarked result uploaded.');
    }

    public function destroy(Request $request, Order $order, LabResult $result): RedirectResponse
    {
        $this->ensureOrderAccessible($request, $order);

        if ((int) $result->order_id !== (int) $order->id) {
            abort(404);
        }

        if ($result->file_path) {
            @unlink(storage_path('app/public/'.$result->file_path));
        }

        $result->delete();

        return back()->with('success', 'Result deleted.');
    }

    public function download(Request $request, Order $order, LabResult $result)
    {
        $this->ensureOrderAccessible($request, $order);

        if ((int) $result->order_id !== (int) $order->id) {
            abort(404);
        }

        $path = storage_path('app/public/'.$result->file_path);
        if (! file_exists($path)) {
            abort(404, 'File not found.');
        }

        return Response::download($path, basename($path));
    }

    private function ensureOrderAccessible(Request $request, Order $order): void
    {
        $user = $request->user();
        if (in_array($user->role, ['lab_manager', 'lab_staff'], true) && (int) $order->lab_id !== (int) $user->lab_id) {
            abort(403, 'Unauthorized order access.');
        }
    }
}
