<?php

declare(strict_types=1);

namespace App\Http\Controllers\Market;

use App\Http\Controllers\Helpers\ResponseHelper;
use App\Models\Market\Courier;
use App\Models\Market\Shipment;
use App\Models\Market\Store;
use App\Models\Market\Customer;
use App\Models\GlobalTransaction;
use Hypervel\Http\Request;
use Hypervel\Support\Facades\Auth;

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

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

        $user = Auth::user();

        $query = Shipment::with(['courier', 'transaction', 'store', 'customer']);

        // filter by store if provided
        if ($storeHash = $request->input('store_hash')) {
            $store = Store::where('hashkey', $storeHash)->first();
            if ($store) {
                $query->where('store_id', $store->id);
            }
        }

        // if not ultimate/admin, restrict to user's shipments
        // (This logic might need adjustment based on how roles are defined)
        // For now, let's just list all and allow filtering
        
        $shipments = $query->orderBy('created_at', 'desc')->get();

        return response()->json([
            'success' => true,
            'data' => $shipments
        ]);
    }

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

        $user = Auth::user();

        $validated = $request->validate([
            'transaction_hash' => 'required|string',
            'store_hash' => 'nullable|string',
            'customer_hash' => 'nullable|string',
            'courier_hash' => 'nullable|string',
            'origin_address' => 'nullable|string',
            'destination_address' => 'nullable|string',
            'shipping_fee' => 'nullable|numeric',
            'estimated_delivery_date' => 'nullable|date',
        ]);

        $transaction = GlobalTransaction::where('hashkey', $validated['transaction_hash'])->first();
        if (!$transaction) {
            return ResponseHelper::returnError('Transaction not found', 404);
        }

        $store = $validated['store_hash'] ? Store::where('hashkey', $validated['store_hash'])->first() : null;
        $customer = $validated['customer_hash'] ? Customer::where('hashkey', $validated['customer_hash'])->first() : null;
        $courier = $validated['courier_hash'] ? Courier::where('hashkey', $validated['courier_hash'])->first() : null;

        $shipment = new Shipment([
            'transaction_id' => $transaction->id,
            'store_id' => $store?->id,
            'customer_id' => $customer?->id,
            'courier_id' => $courier?->id,
            'origin_address' => $validated['origin_address'] ?? $store?->address,
            'destination_address' => $validated['destination_address'] ?? $customer?->address,
            'shipping_fee' => $validated['shipping_fee'] ?? 0,
            'estimated_delivery_date' => $validated['estimated_delivery_date'],
            'status' => 'PENDING',
            'created_by' => $user->id,
        ]);

        if ($shipment->save()) {
            return ResponseHelper::returnSuccessResponse($shipment, $shipment->hashkey, 'Shipment created successfully');
        }

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

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

        $hashkey = $request->input('target');
        $status = $request->input('status');

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

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

        $shipment->status = $status;
        if ($status === 'DELIVERED') {
            $shipment->actual_delivery_date = now();
        }
        $shipment->save();

        return ResponseHelper::returnSuccessResponse($shipment, $shipment->hashkey, 'Shipment status updated');
    }

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

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

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

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'contact_number' => 'nullable|string',
            'type' => 'required|string|in:INTERNAL,EXTERNAL',
        ]);

        $courier = new Courier([
            'name' => $validated['name'],
            'contact_number' => $validated['contact_number'],
            'type' => $validated['type'],
        ]);

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

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