<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Vendor;
use App\Services\AuditService;
use App\Support\EmployeeValidation;
use App\Support\FormTextRules;
use Illuminate\Http\Request;

class VendorController extends Controller
{
    public function __construct(
        protected AuditService $audit
    ) {
        $this->middleware('finance.treasury');
    }

    public function index()
    {
        $vendors = Vendor::orderBy('name')->paginate(15);

        return view('vendors.index', compact('vendors'));
    }

    public function create()
    {
        return view('vendors.create');
    }

    public function store(Request $request)
    {
        $request->merge(EmployeeValidation::normalize($request->only(['email', 'phone'])));
        $validated = $request->validate($this->rules(), $this->messages());
        $validated['status'] = $validated['status'] ?? 'active';
        $validated['company_id'] = auth()->user()->company_id;
        $vendor = Vendor::create($validated);
        $this->audit->log('vendor.created', $vendor);

        return redirect()->route('vendors.index')->with('success', 'Vendor created successfully.');
    }

    public function edit(Vendor $vendor)
    {
        $this->assertTenantRecord($vendor);

        return view('vendors.edit', compact('vendor'));
    }

    public function update(Request $request, Vendor $vendor)
    {
        $this->assertTenantRecord($vendor);
        $request->merge(EmployeeValidation::normalize($request->only(['email', 'phone'])));
        $validated = $request->validate($this->rules(), $this->messages());
        $vendor->update($validated);
        $this->audit->log('vendor.updated', $vendor);

        return redirect()->route('vendors.index')->with('success', 'Vendor updated successfully.');
    }

    public function destroy(Vendor $vendor)
    {
        $this->assertTenantRecord($vendor);
        $vendor->delete();
        $this->audit->log('vendor.deleted', null, ['vendor_id' => $vendor->id]);

        return redirect()->route('vendors.index')->with('success', 'Vendor deleted.');
    }

    /**
     * @return array<string, mixed>
     */
    protected function rules(): array
    {
        return [
            'name' => FormTextRules::notNumericOnly(true, 191),
            'email' => ['nullable', 'email', 'max:191'],
            'phone' => ['nullable', 'digits:10'],
            'address' => FormTextRules::notNumericOnly(false, 500),
            'gstin' => ['nullable', 'string', 'max:50'],
            'status' => ['nullable', 'in:active,inactive'],
        ];
    }

    /**
     * @return array<string, string>
     */
    protected function messages(): array
    {
        return array_merge(FormTextRules::messages(), [
            'phone.digits' => EmployeeValidation::messages()['phone.digits'],
        ]);
    }

    protected function assertTenantRecord(Vendor $vendor): void
    {
        $companyId = auth()->user()?->company_id;
        if ($companyId && (int) $vendor->company_id !== (int) $companyId) {
            abort(403);
        }
    }
}
