<?php

namespace App\Http\Controllers;

use App\Models\Technician;
use App\Models\User;
use App\Models\CurrentContracts;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class TechnicianController extends Controller
{
    public function index(Request $request)
    {
        $user     = Auth::user();
        $supplier = $user->suppliers;

        if (!$supplier) {
            return response()->json(['message' => 'No tienes un perfil de proveedor'], 400);
        }

        $technicians = Technician::with('user')
            ->where('supplier_id', $supplier->id)
            ->get()
            ->map(fn($t) => [
                'id'      => $t->id,
                'user_id' => $t->user_id,
                'name'    => $t->user->name ?? null,
                'email'   => $t->user->email ?? null,
                'phone'   => $t->user->phone ?? null,
            ]);

        return response()->json($technicians);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'user_id' => 'required|numeric|exists:users,id',
        ]);
        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        $user     = Auth::user();
        $supplier = $user->suppliers;

        if (!$supplier) {
            return response()->json(['message' => 'No tienes un perfil de proveedor'], 400);
        }

        $targetUser = User::find($request->user_id);

        if ($targetUser->id === $user->id) {
            return response()->json(['message' => 'No puedes agregarte a ti mismo como técnico'], 422);
        }

        $exists = Technician::where('user_id', $request->user_id)
            ->where('supplier_id', $supplier->id)
            ->exists();

        if ($exists) {
            return response()->json(['message' => 'Este usuario ya es técnico de tu empresa'], 422);
        }

        $technician = Technician::create([
            'user_id'     => $request->user_id,
            'supplier_id' => $supplier->id,
        ]);

        $targetUser->role_id = 8;
        $targetUser->save();

        return response()->json([
            'id'      => $technician->id,
            'user_id' => $technician->user_id,
            'name'    => $targetUser->name,
            'email'   => $targetUser->email,
            'phone'   => $targetUser->phone,
        ], 201);
    }

    public function destroy($id)
    {
        $user     = Auth::user();
        $supplier = $user->suppliers;

        if (!$supplier) {
            return response()->json(['message' => 'No tienes un perfil de proveedor'], 400);
        }

        $technician = Technician::where('id', $id)
            ->where('supplier_id', $supplier->id)
            ->first();

        if (!$technician) {
            return response()->json(['message' => 'Técnico no encontrado'], 404);
        }

        // Revertir role a "Usuario" solo si no pertenece a otro proveedor
        $otherSuppliers = Technician::where('user_id', $technician->user_id)
            ->where('supplier_id', '!=', $supplier->id)
            ->exists();

        if (!$otherSuppliers) {
            $targetUser = User::find($technician->user_id);
            if ($targetUser && $targetUser->role_id === 8) {
                $targetUser->role_id = 1;
                $targetUser->save();
            }
        }

        $technician->delete();

        return response()->json(['message' => 'Técnico eliminado exitosamente']);
    }

    public function find(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
        ]);
        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        $user     = Auth::user();
        $supplier = $user->suppliers;

        if (!$supplier) {
            return response()->json(['message' => 'No tienes un perfil de proveedor'], 400);
        }

        $targetUser = User::where('email', $request->email)->first();

        if (!$targetUser) {
            return response()->json(['message' => 'Usuario no encontrado'], 404);
        }

        $alreadyInTeam = Technician::where('user_id', $targetUser->id)
            ->where('supplier_id', $supplier->id)
            ->exists();

        return response()->json([
            'id'            => $targetUser->id,
            'name'          => $targetUser->name,
            'email'         => $targetUser->email,
            'phone'         => $targetUser->phone,
            'already_in_team' => $alreadyInTeam,
        ]);
    }

    public function assign(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'contract_id'   => 'required|numeric|exists:current_contracts,id',
            'technician_id' => 'nullable|numeric|exists:technicians,id',
        ]);
        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        $user     = Auth::user();
        $supplier = $user->suppliers;

        if (!$supplier) {
            return response()->json(['message' => 'No tienes un perfil de proveedor'], 400);
        }

        $contract = CurrentContracts::find($request->contract_id);

        if ($contract->supplier_id !== $supplier->id) {
            return response()->json(['message' => 'No autorizado'], 403);
        }

        if ($request->technician_id) {
            $technician = Technician::where('id', $request->technician_id)
                ->where('supplier_id', $supplier->id)
                ->first();

            if (!$technician) {
                return response()->json(['message' => 'El técnico no pertenece a tu empresa'], 422);
            }
        }

        $contract->technical_id = $request->technician_id ?? null;
        $contract->save();

        return response()->json(['message' => 'Técnico asignado exitosamente']);
    }
}
