<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Models\User;
use App\Models\Investment;
use App\Models\Ownership;
use App\Models\Bid;
use App\Models\Sell;
use App\Models\Deposit;
use App\Models\Withdrawal;
use App\Models\AgentWithdrawal;
use App\Models\Product;
use App\Models\Vendor;
use Exception;

class AccountDeletionController extends Controller
{
    /**
     * Delete user account and all related data
     */
    public function deleteAccount(Request $request)
    {
        try {
            $user = Auth::user();
            
            if (!$user) {
                return response()->json([
                    'message' => 'User not found'
                ], 404);
            }

            DB::beginTransaction();

            // Log the deletion attempt
            Log::info("Account deletion initiated for user: {$user->id} - {$user->email}");

            // 1. Delete AI Trading Bots (Investments)
            Investment::where('user_id', $user->id)->delete();
            
            // 2. Delete Ownerships (Inventory)
            Ownership::where('user_id', $user->id)->delete();
            
            // 3. Delete Bids
            Bid::where('user_id', $user->id)->delete();
            
            // 4. Delete Sells
            Sell::where('user_id', $user->id)->delete();
            
            // 5. Delete Deposit Records
            Deposit::where('user_id', $user->id)->delete();
            
            // 6. Delete Withdrawal Records
            Withdrawal::where('user_id', $user->id)->delete();
            
            // 7. Delete Agent Withdrawal Records
            AgentWithdrawal::where('user_id', $user->id)->delete();
            
            // 8. Handle Vendor Products (if user is a vendor)
            $vendor = Vendor::where('user_id', $user->id)->first();
            if ($vendor) {
                // Delete vendor's products
                Product::where('user_id', $user->id)->delete();
                
                // Delete vendor record
                $vendor->delete();
            }
            
            // 9. Update referrals (remove this user as referrer from downstream users)
            // This ensures orphaned users don't point to a deleted account
            User::where('referrer_id', $user->id)->update(['referrer_id' => null]);
            
            // 10. Finally, delete the user account
            $userId = $user->id;
            $userEmail = $user->email;
            
            $user->delete();
            
            // Log successful deletion
            Log::info("Account successfully deleted for user ID: {$userId} - {$userEmail}");

            DB::commit();

            // Logout the user
            Auth::logout();
            
            // Invalidate session
            $request->session()->invalidate();
            $request->session()->regenerateToken();

            return response()->json([
                'message' => 'Account deleted successfully'
            ], 200);

        } catch (Exception $e) {
            DB::rollBack();
            
            Log::error("Account deletion failed: " . $e->getMessage());
            
            return response()->json([
                'message' => 'Failed to delete account. Please try again or contact support.',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }
}