<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\Service;
use App\Services\FeeEngineService;
use App\Services\ServiceVersionService;

class ServiceMasterController extends Controller
{
    public function show($id)
    {
        $tenantId = auth()->user()->tenant_id;
        $service = Service::where('tenant_id', $tenantId)
            ->with(['category', 'authority', 'forms.sections.fields', 'documentRules.documentType', 'feeComponents', 'workflowStages.transitionsFrom', 'versions'])
            ->findOrFail($id);

        return view('tenant.services.show', compact('service'));
    }

    public function duplicate($id)
    {
        $tenantId = auth()->user()->tenant_id;
        $service = Service::where('tenant_id', $tenantId)->findOrFail($id);

        $newService = $service->replicate();
        $newService->service_code = $service->service_code.'-COPY-'.rand(10, 99);
        $newService->name_en = $service->name_en.' (Copy)';
        $newService->status = 'draft';
        $newService->version = 1;
        $newService->save();

        return redirect()->route('app.services.show', $newService->id)->with('status', 'Service duplicated successfully as '.$newService->name_en);
    }

    public function testMode($id, FeeEngineService $feeEngine)
    {
        $tenantId = auth()->user()->tenant_id;
        $service = Service::where('tenant_id', $tenantId)
            ->with(['forms.sections.fields', 'documentRules', 'feeComponents', 'workflowStages'])
            ->findOrFail($id);

        $calculatedFees = $feeEngine->calculateServiceFees($service, ['priority' => 'normal']);

        return view('tenant.services.test_mode', compact('service', 'calculatedFees'));
    }

    public function publish($id, ServiceVersionService $versionService)
    {
        $tenantId = auth()->user()->tenant_id;
        $service = Service::where('tenant_id', $tenantId)->findOrFail($id);

        $version = $versionService->publishVersion($service, 'Service published to active catalog.');

        return redirect()->route('app.services.show', $service->id)->with('status', '🎉 Service published successfully as Version v'.$version->version_number);
    }
}
