<?php

namespace App\Http\Controllers\ComputerRegister;

use App\Http\Requests\ComputerRegisterRequest;
use App\Models\Computer;
use App\Models\Enum\ComputerStatusEnum;
use App\Models\Side;

class ComputerRegisterController
{
    private const DEFAULT_XB_COMPUTER_TYPES = ["Internet i+", "OPAC"];
    private const DEFAULT_XB_COMPUTER_ID = ["Internet i+" => 1, "OPAC" => 2];

    public function computerRegisterAction(ComputerRegisterRequest $request)
    {
        $computerRegisterRequestBody = $request->getData();

        $side = Side::where("identifier", $computerRegisterRequestBody->getSideCode())->first();
        if (!$side) {
            return response()->json(["message" => "Side not found"], 404);
        }

        $computerDoesntExist = Computer::where("side_id", $side->id)
            ->where(function ($query) use ($computerRegisterRequestBody) {
                $query->where("mac_address", $computerRegisterRequestBody->getMacAddress())
                    ->orWhere("ip_address", $computerRegisterRequestBody->getIpAddress());
            })
            ->doesntExist()
        ;
        if (!$computerDoesntExist) {
            return response()->json(["message" => "Computer is already registered"], 409);
        }

        if (!in_array($computerRegisterRequestBody->getType(), self::DEFAULT_XB_COMPUTER_TYPES)) {
            return response()->json(["message" => "Invalid type"], 400);
        }

        $computer = Computer::create([
            "name" => $computerRegisterRequestBody->getName(),
            "mac_address" => $computerRegisterRequestBody->getMacAddress(),
            "ip_address" => $computerRegisterRequestBody->getIpAddress(),
            "side_id" => $side->id,
            "computer_status_id" => ComputerStatusEnum::ID[ComputerStatusEnum::ACTIVE],
            "computer_type_id" => self::DEFAULT_XB_COMPUTER_ID[$computerRegisterRequestBody->getType()],
            "reserved" => false,
            "maintenance_required" => false,
        ]);
        if (!$computer) {
            return response()->json(["message" => "Failed to create computer"], 409);
        }

        return response()->json([], 201);
    }
}
