<?php

namespace App\Http\Controllers\Institution;

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

class SynapseContactController extends Controller
{
    public function store(Request $request, int $institution): JsonResponse
    {
        $institution = Institution::find($institution);

        if (!$institution) {
            return response()->json([
                'success' => false,
                'message' => 'Institution not found.',
            ], 404);
        }

        if (!auth()->user()->can('institutions.contacts.create')) {
            return response()->json(['success' => false, 'message' => 'Unauthorised.'], 403);
        }

        $data = $request->validate([
            'job_title' => 'nullable|string|max:255',
            'email'     => 'nullable|email|max:255',
            'telephone' => 'nullable|string|max:255',
        ]);

        $email = $data['email'] ?? null;

        // Duplicate check — skip if a contact with this email already exists
        if ($email && $institution->contacts()->where('email', $email)->exists()) {
            return response()->json([
                'success' => false,
                'message' => 'A contact with this email address already exists on this institution.',
            ], 409);
        }

        $isFirst = $institution->contacts()->count() === 0;

        $institution->contacts()->create([
            'job_title'  => $data['job_title'] ?? null,
            'email'      => $email,
            'telephone'  => $data['telephone'] ?? null,
            'is_primary' => $isFirst,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Contact added to ' . $institution->display_name . '.',
        ]);
    }
}
