<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ClientController extends Controller
{
    public function index(): JsonResponse
    {
        return response()->json(['data' => DB::table('tenants')->latest('id')->paginate(25)]);
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:180'],
            'legal_name' => ['nullable', 'string', 'max:220'],
            'domain' => ['nullable', 'string', 'max:180'],
            'employee_limit' => ['required', 'integer', 'min:0'],
            'branch_limit' => ['required', 'integer', 'min:0'],
            'device_limit' => ['required', 'integer', 'min:0'],
            'timezone' => ['required', 'string', 'max:80'],
            'currency' => ['required', 'string', 'size:3'],
        ]);

        $id = DB::table('tenants')->insertGetId($data + [
            'status' => 'trial',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return response()->json(['data' => DB::table('tenants')->find($id)], 201);
    }

    public function show(int $client): JsonResponse
    {
        return response()->json(['data' => DB::table('tenants')->find($client)]);
    }

    public function update(Request $request, int $client): JsonResponse
    {
        $data = $request->only(['name', 'legal_name', 'domain', 'status', 'employee_limit', 'branch_limit', 'device_limit', 'timezone', 'currency']);

        DB::table('tenants')->where('id', $client)->update($data + ['updated_at' => now()]);

        return response()->json(['data' => DB::table('tenants')->find($client)]);
    }

    public function destroy(int $client): JsonResponse
    {
        DB::table('tenants')->where('id', $client)->update(['status' => 'suspended', 'updated_at' => now()]);

        return response()->json(status: 204);
    }

    public function suspend(int $client): JsonResponse
    {
        DB::table('tenants')->where('id', $client)->update(['status' => 'suspended', 'updated_at' => now()]);

        return response()->json(['status' => 'suspended']);
    }
}
