<?php

namespace App\Modules\Products\UnitModule\Domain\Services;

use App\Modules\Products\UnitModule\Domain\Repositories\UnitRepositoryInterface;
use App\Modules\Products\UnitModule\Domain\Models\Unit;
use App\Models\NotificationModel;
use App\Jobs\SendSignupEmailJob;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\View;

class UpdateUnitApprovalService
{
    public function __construct(private UnitRepositoryInterface $units) {}

    public function handle(int $unitId, int $approvalStatus): array
    {
        $unit = $this->units->findById($unitId);

        if (!$unit) {
            return ['success' => false, 'message' => 'Unit not found.'];
        }

        $user = User::find($unit->user_id);
        $unit->approval_status = $approvalStatus;
        $unit->is_notify_view = $approvalStatus;
        $unit->save();

        // Approval text
        $statusText = $approvalStatus == 1 ? 'approved' : 'unapproved';
        $subject = "Unit " . ucfirst($statusText) . " Notification";
        $approvalMessage = "The unit '" . ($unit->name ?? "") . "' has been {$statusText} by Power Cozmo.";

        // Send Email
        if ($user) {
            $dataSend = [
                'name' => $user->name ?? '',
                'email' => $user->email ?? '',
                'base_url' => url('/public'),
                'subject' => $subject,
                'approval_message' => $approvalMessage,
                'content' => View::make('emails.category_approval', [
                    'name' => $user->name ?? '',
                    'approval_message' => $approvalMessage,
                    'base_url' => url('/public')
                ])->render(),
            ];

            dispatch(new SendSignupEmailJob($dataSend));
        }

        // Create Notification
        NotificationModel::create([
            'from_user_id' => Auth::id(),
            'from_user_name' => 'Power Cozmo',
            'type' => 'unit',
            'updated_id' => $unit->id,
            'url_key' => '/seller/units',
            'user_id' => $unit->user_id,
            'title' => "Unit " . ucfirst($statusText),
            'message' => $approvalMessage,
        ]);

        return ['success' => true, 'message' => "Unit {$statusText} successfully."];
    }
}
