<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Channel;
use App\Models\Sale;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class ChannelController extends Controller
{
    /**
     * GET /api/channels
     */
    public function index()
    {
        $channels = Channel::orderBy('name')->get();

        return response()->json($channels);
    }

    /**
     * POST /api/channels
     */
    public function store(Request $request)
    {
        $data = $request->validate([
            'name'        => ['required', 'string', 'max:100', 'unique:channels'],
            'description' => ['nullable', 'string'],
        ]);

        $channel = Channel::create($data);

        return response()->json($channel, 201);
    }

    /**
     * GET /api/channels/{id}
     */
    public function show(Channel $channel)
    {
        return response()->json($channel);
    }

    /**
     * PUT /api/channels/{id}
     */
    public function update(Request $request, Channel $channel)
    {
        $data = $request->validate([
            'name'        => ['sometimes', 'string', 'max:100', Rule::unique('channels')->ignore($channel->id)],
            'description' => ['nullable', 'string'],
        ]);

        $channel->update($data);

        return response()->json($channel);
    }

    /**
     * DELETE /api/channels/{id}
     */
    public function destroy(Channel $channel)
    {
        // Optional: prevent deletion if used in sales
        $usedInSales = Sale::where('channel', $channel->name)->exists();
        if ($usedInSales) {
            return response()->json([
                'message' => 'Channel tidak bisa dihapus karena sudah memiliki data transaksi penjualan.',
            ], 422);
        }

        $channel->delete();

        return response()->json(['message' => 'Channel berhasil dihapus.']);
    }
}
