<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\ColorRequest;
use App\Models\Color;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class ColorController extends Controller
{
    public function index(): View
    {
        $colors = Color::withCount('variants')->orderBy('name')->paginate(20);

        return view('admin.colors.index', compact('colors'));
    }

    public function store(ColorRequest $request): RedirectResponse
    {
        Color::create($request->validated());

        return back()->with('success', 'Color added.');
    }

    public function update(ColorRequest $request, Color $color): RedirectResponse
    {
        $color->update($request->validated());

        return back()->with('success', 'Color updated.');
    }

    public function destroy(Color $color): RedirectResponse
    {
        if ($color->variants()->exists()) {
            return back()->with('error', 'This color is used by existing product variants.');
        }

        $color->delete();

        return back()->with('success', 'Color deleted.');
    }
}
