<?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 PackageController extends Controller
{
    public function index(): JsonResponse
    {
        return response()->json(['data' => DB::table('packages')->latest('id')->get()]);
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'monthly_price' => ['required', 'numeric', 'min:0'],
            'yearly_price' => ['required', 'numeric', 'min:0'],
            'employee_limit' => ['required', 'integer', 'min:0'],
            'branch_limit' => ['required', 'integer', 'min:0'],
            'device_limit' => ['required', 'integer', 'min:0'],
            'is_trial' => ['boolean'],
            'modules' => ['array'],
        ]);

        $modules = $data['modules'] ?? [];
        unset($data['modules']);

        $id = DB::transaction(function () use ($data, $modules) {
            $packageId = DB::table('packages')->insertGetId($data + ['created_at' => now(), 'updated_at' => now()]);

            foreach ($modules as $module) {
                DB::table('package_modules')->insert(['package_id' => $packageId, 'module_key' => $module]);
            }

            return $packageId;
        });

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

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

    public function update(Request $request, int $package): JsonResponse
    {
        DB::table('packages')->where('id', $package)->update($request->except('modules') + ['updated_at' => now()]);

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

    public function destroy(int $package): JsonResponse
    {
        DB::table('packages')->where('id', $package)->delete();

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