<?php

namespace App\Http\Controllers;

use App\Models\Workspace;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class WorkspaceController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'color' => 'nullable|string|max:7',
        ]);

        $workspace = Auth::user()->workspaces()->create($validated);
        $workspace->members()->attach(Auth::id(), ['role' => 'admin']);

        return redirect()->back()->with('success', 'Workspace created!');
    }

    public function update(Request $request, Workspace $workspace)
    {
        if ($workspace->user_id !== Auth::id()) abort(403);

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'color' => 'nullable|string|max:7',
        ]);

        $workspace->update($validated);

        return redirect()->back()->with('success', 'Workspace updated!');
    }

    public function destroy(Workspace $workspace)
    {
        if ($workspace->user_id !== Auth::id()) abort(403);
        
        $workspace->delete();

        return redirect()->route('home')->with('success', 'Workspace deleted!');
    }
}
