<?php

namespace App\Http\Controllers\Buyer;

use App\Enum\Status;
use App\Models\Buyer\Buyer;
use App\Models\Role;
use App\Models\Term;
use App\Models\User;
use App\Models\DxCustomer;
use Illuminate\Support\Str;
use App\Http\Controllers\Controller;
use App\Http\Requests\Buyer\RegisterRequest;
use App\Models\DxService;
use App\Repositories\Contracts\UserRepositoryInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;

class RegisterController extends Controller
{
    public function __construct(
        protected UserRepositoryInterface $userRepository
    ) {}

    /**
     * Show the registration form (Blade view).
     */
    public function index(Request $request): View
    {
        $services = DxCustomer::whereStatus(Status::ACTIVE)->get();
        return view('auth.buyers.register', compact('services'));
    }

    /**
     * Store a newly registered buyer.
     * Works for both API (JSON) and Blade (redirect).
     */
    public function store(RegisterRequest $request): JsonResponse|RedirectResponse
    {
        try {
            DB::beginTransaction();

            $user = $this->userRepository->createBuyer([
                'first_name' => $request->input('first_name'),
                'last_name' => $request->input('last_name'),
                'email' => $request->input('email'),
                'phone' => $request->input('phone'),
                'password' => $request->input('password'),
            ]);

            // Auto-login the user
            $this->userRepository->authenticate([
                'email' => $request->input('email'),
                'password' => $request->input('password'),
            ]);

            DB::commit();

            // Return JSON for API requests
            if ($request->expectsJson() || $request->wantsJson()) {
                return response()->json([
                    'success' => true,
                    'message' => 'Buyer registered successfully',
                    'data' => [
                        'user' => [
                            'id' => $user->uuid,
                            'first_name' => $user->first_name,
                            'last_name' => $user->last_name,
                            'email' => $user->email,
                        ],
                    ],
                ], 201);
            }

            // Return redirect for Blade requests
            return redirect()->route('buyers.dashboard')->with('success', 'Buyer registered successfully');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Buyer registration error: ' . $e->getMessage(), $e->getTrace());

            // Return JSON for API requests
            if ($request->expectsJson() || $request->wantsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Registration failed. Please try again.',
                    'error' => config('app.debug') ? $e->getMessage() : null,
                ], 500);
            }

            // Return redirect with error for Blade requests
            return back()
                ->withInput()
                ->withErrors(['error' => 'Registration failed. Please try again.']);
        }
    }
}
