<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Contact;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ContactController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = $request->user()->contacts();

        if ($request->has('search')) {
            $query->search($request->search);
        }

        $contacts = $query->orderBy('name')->get();

        return response()->json([
            'success' => true,
            'data' => $contacts,
        ]);
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name'     => 'required|string|max:255',
            'email'    => 'nullable|string|email|max:255',
            'phone'    => 'nullable|string|max:50',
            'type'     => 'in:privat,arbeit,kunde,sonstiges',
            'notes'    => 'nullable|string|max:2000',
            'birthday' => 'nullable|date',
        ]);

        $contact = $request->user()->contacts()->create($validated);

        return response()->json([
            'success' => true,
            'data' => $contact,
            'message' => 'Kontakt erstellt.',
        ], 201);
    }

    public function update(Request $request, string $id): JsonResponse
    {
        $contact = $request->user()->contacts()->findOrFail($id);

        $validated = $request->validate([
            'name'     => 'sometimes|string|max:255',
            'email'    => 'nullable|string|email|max:255',
            'phone'    => 'nullable|string|max:50',
            'type'     => 'in:privat,arbeit,kunde,sonstiges',
            'notes'    => 'nullable|string|max:2000',
            'birthday' => 'nullable|date',
        ]);

        $contact->update($validated);

        return response()->json([
            'success' => true,
            'data' => $contact->fresh(),
            'message' => 'Kontakt aktualisiert.',
        ]);
    }

    public function destroy(Request $request, string $id): JsonResponse
    {
        $contact = $request->user()->contacts()->findOrFail($id);
        $contact->delete();

        return response()->json([
            'success' => true,
            'data' => null,
            'message' => 'Kontakt gelöscht.',
        ]);
    }
}
