<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Tenant;
use App\Services\TenantService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;

class AuthController extends Controller
{
    protected $tenantService;

    public function __construct(TenantService $tenantService)
    {
        $this->tenantService = $tenantService;
    }

    /**
     * Register a new grocery business (Tenant) and default user (Manager).
     */
    public function register(Request $request)
    {
        $validated = $request->validate([
            'business_name' => 'required|string|max:255',
            'domain' => 'required|string|unique:tenants,domain|max:255', // subdomain
            'name' => 'required|string|max:255', // User name
            'email' => 'required|email|unique:users,email',
            'phone_number' => 'required|string|unique:users,phone_number|regex:/^01[3-9][0-9]{8}$/',
        ]);

        try {
            DB::beginTransaction();

            // 1. Prepare Tenant Data
            $dbName = 'tenant_' . str_replace('-', '_', Str::slug($validated['domain']));
            $tenantData = [
                'name' => $validated['business_name'],
                'domain' => $validated['domain'],
                'database_name' => $dbName,
                'status' => 'active',
            ];

            // 2. Prepare User Data (Manager)
            $generatedPassword = Str::random(12);
            $userData = [
                'name' => $validated['name'],
                'email' => $validated['email'],
                'phone_number' => $validated['phone_number'],
                'password' => $generatedPassword,
            ];

            // 3. Create Tenant and Users via Service
            $tenant = $this->tenantService->createTenant($tenantData, $userData);

            // 4. Send Credentials to Manager via Email
            $user = User::where('email', $validated['email'])->first();
            try {
                Mail::to($user->email)->send(new \App\Mail\UserCredentialsMail($user, $generatedPassword, true));
            } catch (\Exception $e) {
                \Illuminate\Support\Facades\Log::error('Failed to send registration email: ' . $e->getMessage());
            }

            DB::commit();

            return response()->json([
                'message' => 'Registration successful. Manager password has been sent to your email.',
                'tenant' => $tenant,
                'user' => $user,
            ], 201);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => 'Registration failed: ' . $e->getMessage()], 500);
        }
    }

    /**
     * Admin activates user.
     */
    public function activateUser(Request $request)
    {
        // Only SaaS Admin should access this (middleware check in route)
        $validated = $request->validate([
            'user_id' => 'required|exists:users,id',
        ]);

        $user = User::findOrFail($validated['user_id']);

        if ($user->status === 'active') {
            return response()->json(['message' => 'User already active'], 400);
        }

        // Generate temp password
        $tempPassword = Str::random(10);
        $user->password = Hash::make($tempPassword);
        $user->status = 'active';
        $user->save();

        // Send email (simulated for now)
        // Mail::raw("Your account has been activated. Password: $tempPassword", function ($message) use ($user) {
        //     $message->to($user->email)->subject('Account Activated');
        // });
        // Using log for now as mailer might not be configured
        \Log::info("User {$user->email} activated. Temp Password: {$tempPassword}");

        return response()->json([
            'message' => 'User activated successfully. Credentials sent to email.',
            // Returning password here for debug purposes as requested "debug info"
            'debug_password' => $tempPassword 
        ]);
    }

    /**
     * Login
     */
    public function login(Request $request)
    {
        $validated = $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        $user = User::where('email', $validated['email'])->first();

        if (!$user || !Hash::check($validated['password'], $user->password)) {
            return response()->json(['message' => 'Invalid credentials'], 401);
        }

        if ($user->status !== 'active') {
            return response()->json(['message' => 'Account is inactive'], 403);
        }

        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'message' => 'Login successful',
            'token' => $token,
            'user' => $user,
            'role' => $user->getRoleNames(),
            'tenant' => $user->tenant,
        ]);
    }
}
