<?php

namespace App\Http\Controllers;

use App\Http\Requests\State\StoreStateRequest;
use App\Http\Requests\State\UpdateStateRequest;
use App\Http\Resources\StateResource;
use App\Models\State;
use Illuminate\Support\Facades\Auth;

class StateController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth:sanctum', 'role:company_admin,staff'])->only(['show', 'edit']);
        $this->middleware(['auth:sanctum', 'role:company_admin'])->only(['update']);
    }

    public function index()
    {
        $user = Auth::user();

        $states = State::query()
            ->where('company_id', $user->company_id)
            ->get();

        return $this->success([
            'data' => StateResource::collection($states),
        ]);
    }

    public function store(StoreStateRequest $request)
    {
        $user = Auth::user();

        $validatedData = $request->validated();

        $state = State::create([
            'customer_id' => $user->customer_id,
            'name' => $validatedData['name'],
            'code' => $validatedData['code'],
        ]);

        return $this->success([
            'data' => new StateResource($state),
            'message' => 'State created successfully.',
        ]);
    }

    public function show($id)
    {
        $state = State::findOrFail($id);

        return $this->success([
            'data' => new StateResource($state),
        ]);
    }

    public function edit($id)
    {
        $state = State::findOrFail($id);

        return $this->success([
            'data' => new StateResource($state),
        ]);
    }

    public function update(UpdateStateRequest $request, $id)
    {
        $validatedData = $request->validated();

        $state = State::findOrFail($id);
        $state->update($validatedData);

        return $this->success([
            'message' => 'State updated successfully.',
            'data' => new StateResource($state),
        ]);
    }
}
