<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Enums\AccountType;
use App\Enums\ProfessionalVerificationStatus;
use App\Http\Controllers\Controller;
use App\Http\Requests\Profile\UpdateProfileRequest;
use App\Http\Resources\ProfessionalProfileResource;
use App\Models\ProfessionalProfile;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class ProfileController extends Controller
{
    /**
     * § 10 — affiche le profil professionnel de l’utilisateur connecté.
     */
    public function show(Request $request): JsonResponse
    {
        $user = $request->user();
        $profile = $this->resolveProfile($user);
        $profile->loadMissing(['user:id,name,email,phone', 'city:id,name']);

        return response()->json([
            'data' => (new ProfessionalProfileResource($profile))->resolve(),
        ]);
    }

    /**
     * § 10 — mise à jour : nom professionnel, téléphone utilisateur, bio, photo.
     * Les compteurs (total_requests, etc.) sont ignorés même s’ils sont envoyés.
     */
    public function update(UpdateProfileRequest $request): JsonResponse
    {
        $user = $request->user();

        DB::transaction(function () use ($request, $user): void {
            $profile = $this->resolveProfile($user);

            if ($request->has('phone')) {
                $user->forceFill(['phone' => $request->validated('phone')])->save();
            }

            $profileData = [];

            if ($request->has('professional_name')) {
                $profileData['professional_name'] = $request->validated('professional_name');
            }

            if ($request->has('bio')) {
                $profileData['bio'] = $request->validated('bio');
            }

            if ($request->hasFile('photo')) {
                $previous = $profile->logo_or_photo;
                if ($previous !== null && $previous !== '' && Storage::disk('public')->exists($previous)) {
                    Storage::disk('public')->delete($previous);
                }
                $storedPath = $request->file('photo')->store('profile-photos', 'public');
                $profileData['logo_or_photo'] = $storedPath;
            }

            if ($profileData !== []) {
                $profile->update($profileData);
            }
        });

        $profile = $this->resolveProfile($user->fresh());
        $profile->loadMissing(['user:id,name,email,phone', 'city:id,name']);

        return response()->json([
            'data' => (new ProfessionalProfileResource($profile))->resolve(),
        ]);
    }

    private function resolveProfile(User $user): ProfessionalProfile
    {
        $accountTypeValue = $user->account_type?->value ?? AccountType::IndependentAgent->value;

        return $user->professionalProfile()->firstOrCreate(
            ['user_id' => $user->id],
            [
                'professional_name' => $user->name,
                'profile_type' => $accountTypeValue,
                'logo_or_photo' => null,
                'city_id' => null,
                'bio' => null,
                'phone_visible' => false,
                'email_visible' => false,
                'verification_status' => ProfessionalVerificationStatus::Pending,
            ],
        );
    }
}
