<?php

declare(strict_types=1);

namespace App\Http\Controllers\Market;

use App\Http\Controllers\Helpers\ResponseHelper;
use App\Models\Market\FarmerProfile;
use App\Models\Market\Organization;
use App\Models\User;
use Hypervel\Http\Request;
use Hypervel\Support\Facades\Auth;

use App\Http\Controllers\Helpers\Permissions\UserPermissions;
use App\Enums\UserActions;

class FarmerController
{
    public function registerFarmer(Request $request)
    {
        $currentUser = Auth::user();
        if (!$currentUser) {
            return ResponseHelper::returnUnauthorized();
        }

        $validated = $request->validate([
            'user_hash' => 'nullable|string',
            'farm_name' => 'required|string|max:255',
            'farm_location' => 'nullable|string',
            'organization_hash' => 'nullable|string',
            'main_crops' => 'nullable|array',
        ]);

        // Determine the target user - if user_hash provided, use that user; otherwise use current user
        if (!empty($validated['user_hash'])) {
            $user = User::where('hashkey', $validated['user_hash'])->first();
            if (!$user) {
                return ResponseHelper::returnError('User not found', 404);
            }
        } else {
            $user = $currentUser;
        }

        $organization = $validated['organization_hash'] ? Organization::where('hashkey', $validated['organization_hash'])->first() : null;

        // Check if user already has a farmer profile
        $existingProfile = FarmerProfile::where('user_id', $user->id)->first();
        if ($existingProfile) {
            return ResponseHelper::returnError('User already has a farmer profile');
        }

        $profile = new FarmerProfile([
            'user_id' => $user->id,
            'organization_id' => $organization?->id,
            'farm_name' => $validated['farm_name'],
            'farm_location' => $validated['farm_location'],
            'main_crops' => $validated['main_crops'],
            'verification_status' => 'VERIFIED',
            'created_by' => $currentUser->id,
        ]);

        if ($profile->save()) {
            return ResponseHelper::returnSuccessResponse($profile, $profile->hashkey, 'Farmer profile created and pending verification');
        }

        return ResponseHelper::returnError('Failed to create farmer profile');
    }

    public function listFarmers(Request $request)
    {
        if (!UserPermissions::isActionPermitted(Auth::user()->acct_type, UserActions::ViewFarmers)) {
            return ResponseHelper::returnUnauthorized();
        }

        $farmers = FarmerProfile::with(['user', 'organization'])->orderBy('created_at', 'desc')->get();
        return response()->json([
            'success' => true,
            'data' => $farmers
        ]);
    }

    public function verifyFarmer(Request $request)
    {
        if (!UserPermissions::isActionPermitted(Auth::user()->acct_type, UserActions::VerifyFarmer)) {
            return ResponseHelper::returnUnauthorized();
        }

        $hashkey = $request->input('target');
        $status = $request->input('status'); // VERIFIED, REJECTED

        if (!$hashkey || !$status) {
            return ResponseHelper::returnIncorrectDetails();
        }

        $profile = FarmerProfile::where('hashkey', $hashkey)->first();
        if (!$profile) {
            return ResponseHelper::returnError('Profile not found', 404);
        }

        $profile->verification_status = $status;
        $profile->save();

        return ResponseHelper::returnSuccessResponse($profile, $profile->hashkey, 'Farmer verification status updated');
    }

    public function listOrganizations()
    {
        if (!UserPermissions::isActionPermitted(Auth::user()->acct_type, UserActions::ViewOrganizations)) {
            return ResponseHelper::returnUnauthorized();
        }

        $orgs = Organization::where('is_active', true)->get();
        return response()->json([
            'success' => true,
            'data' => $orgs
        ]);
    }

    public function createOrganization(Request $request)
    {
        if (!UserPermissions::isActionPermitted(Auth::user()->acct_type, UserActions::CreateOrganization)) {
            return ResponseHelper::returnUnauthorized();
        }

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|string|in:COOPERATIVE,ASSOCIATION,COMPANY',
            'address' => 'nullable|string',
        ]);

        $org = new Organization([
            'name' => $validated['name'],
            'type' => $validated['type'],
            'address' => $validated['address'],
        ]);

        if ($org->save()) {
            return ResponseHelper::returnSuccessResponse($org, $org->hashkey, 'Organization created');
        }

        return ResponseHelper::returnError('Failed to create organization');
    }
}
