<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\GuardianLog;
use App\Models\Ad;
use App\Models\User;
use Illuminate\Http\Request;

class GuardianDashboardController extends Controller
{
    public function index()
    {
        $logs = GuardianLog::with('target')->latest()->paginate(20);
        return view('admin.guardian.logs', compact('logs'));
    }

    public function overwrite($id)
    {
        $log = GuardianLog::findOrFail($id);

        if ($log->is_overwritten) {
            return back()->with('error', 'This action has already been overwritten.');
        }

        // Logic to reverse the action
        $success = false;
        
        switch ($log->action) {
            case 'AUTO_BAN':
                if ($log->target_type === 'User') {
                    $user = User::find($log->target_id);
                    if ($user) {
                        $user->update(['status' => 'active']); // Assuming 'active' is the status
                        $success = true;
                    }
                }
                break;

            case 'SUSPEND':
            case 'FLAG_FOR_REVIEW':
                if ($log->target_type === 'Ad') {
                    $ad = Ad::find($log->target_id);
                    if ($ad) {
                        $ad->update(['status' => 'Active']);
                        $success = true;
                    }
                }
                break;
                
            // For SUGGEST_CHANGES, there's nothing to "undo" on DB, just marking it is enough
            case 'SUGGEST_CHANGES':
                $success = true; 
                break;
        }

        if ($success) {
            $log->update([
                'is_overwritten' => true,
                'admin_id' => auth()->id()
            ]);
            return back()->with('success', 'AI Action Overwritten successfully.');
        }

        return back()->with('error', 'Could not reverse action. Target might be missing.');
    }
}
