<?php

namespace App\Http\Controllers;

use App\Enums\BulkActionEnum;
use App\Enums\StatusEnum;
use App\Models\Workspace;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Inertia\Inertia;

class WorkspaceController extends Controller
{
    public function settings()
    {
        $user  = auth_user();

        $workspaces = Workspace::query()
            ->search(['name', 'email'])
            ->filter(['status'])
            ->orderByRaw("id = ? DESC", [$user->current_workspace_id])
            ->paginate(paginateNumber())
            ->withQueryString();



        return Inertia::render('Workspace/Settings', [
            'workspaces' => $workspaces
        ]);

    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string',
            'email' => 'nullable|email'
        ]);


        Workspace::create([
            'user_id' => auth_user()->id,
            'name' => $request->input('name'),
            'email' => $request->input('email'),
            'status' => StatusEnum::true->status()
        ]);

        return redirect()->route('user.workspace.settings')->with('success', 'workspace created');

    }



    public function statusUpdate(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:workspaces,id',
            'status' => 'required',
        ]);

        try {
            $workspace = Workspace::findOrFail($request->id);
            $workspace->status = $request->status;
            $workspace->save();

            return back()->with('success', 'Workspace status updated successfully');
        } catch (\Exception $e) {
            return back()->with('error', 'Workspace status did not change');

        }
    }


    public function delete(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:workspaces,id'
        ]);

        $workspace = Workspace::findOrFail($request->input('id'));
        if (auth_user()->current_workspace_id == $workspace->id) {
            return redirect()->route('user.workspace.settings')->with('error', 'Can not delete current workspace ,switch first');
        }
        $workspace->delete();

        return redirect()->route('user.workspace.settings')->with('success', 'Workspace deleted');

    }


    public function bulk(Request $request)
    {
        $validated = $request->validate([
            'action' => ['required', Rule::in(BulkActionEnum::values())],
            'ids' => 'required|array',
            'ids.*' => 'integer'
        ]);

        $currentWorkspaceId = auth_user()->current_workspace_id;

        if (
            BulkActionEnum::from($validated['action']) === BulkActionEnum::DELETE
            && in_array($currentWorkspaceId, $validated['ids'])
        ) {
            return redirect()->route('user.workspace.settings')
                ->with('error', 'Cannot delete current workspace. Please switch first.');
        }

        $query = Workspace::whereIn('id', $validated['ids']);

        match (BulkActionEnum::from($validated['action'])) {
            BulkActionEnum::ACTIVATE => $query->update(['status' => StatusEnum::true->status()]),
            BulkActionEnum::INACTIVATE => $query->update(['status' => StatusEnum::false->status()]),
            BulkActionEnum::DELETE => $query->delete(),
        };

        return back()->with('success', "Bulk {$validated['action']} completed.");
    }

    public function switch(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:workspaces,id',
        ]);

        $user = auth()->user();
        $workspaceId = $request->input('id');


        $user->switchToWorkspace($workspaceId);

        return back()->with('success', 'Workspace switched successfully.');
    }

}
