<?php

namespace App\Actions\Jetstream;

use Illuminate\Support\Facades\Log;
use Throwable;

class RestoreProfile
{
    /**
     * Restore a deleted profile if within grace period and not yet anonymized.
     *
     * @param  mixed  $profile
     * @return array
     */
    public function restore($profile)
    {
        try {
            // Check if profile is actually deleted
            if (!$profile->deleted_at) {
                return [
                    'status' => 'error',
                    'message' => 'Profile is not deleted.'
                ];
            }

            // Check if profile has been anonymized (email is the indicator)
            if (str_starts_with($profile->email, 'removed-') && str_ends_with($profile->email, '@remove.ed')) {
                return [
                    'status' => 'error',
                    'message' => 'Profile has been permanently deleted and cannot be restored.'
                ];
            }

            // Check if grace period has expired
            $gracePeriodDays = timebank_config('delete_profile.grace_period_days', 30);
            $gracePeriodExpiry = $profile->deleted_at->addDays($gracePeriodDays);

            if (now()->isAfter($gracePeriodExpiry)) {
                return [
                    'status' => 'error',
                    'message' => 'Grace period has expired. Profile cannot be restored.'
                ];
            }

            // Restore the profile by clearing deleted_at and balance handling data
            $profile->deleted_at = null;
            $profile->comment = null; // Clear stored balance handling preferences
            $profile->save();

            // Clear balance handling cache
            $cacheKey = 'balance_handling_' . get_class($profile) . '_' . $profile->id;
            \Cache::forget($cacheKey);

            // Restore associated accounts (they were never marked deleted during grace period)
            // No need to update accounts as they remain active during grace period

            Log::info('Profile restored', [
                'profile_type' => get_class($profile),
                'profile_id' => $profile->id,
                'profile_name' => $profile->name,
            ]);

            return [
                'status' => 'success',
                'message' => 'Profile has been successfully restored.'
            ];

        } catch (Throwable $e) {
            Log::error('Profile restoration failed', [
                'profile_id' => $profile->id ?? null,
                'error' => $e->getMessage()
            ]);

            return [
                'status' => 'error',
                'message' => $e->getMessage()
            ];
        }
    }
}
