<?php

namespace App\Modules\Tenant\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Responses\ApiResponse;
use App\Models\User;
use App\Modules\Tenant\Models\Company;
use App\Modules\Tenant\Requests\StoreMemberRequest;
use App\Modules\Tenant\Requests\UpdateMemberRoleRequest;
use App\Modules\Tenant\Resources\MemberResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class MemberController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $company = $this->currentCompany($request);

        $members = $company->users()
            ->orderBy('name')
            ->get();

        return ApiResponse::success(MemberResource::collection($members));
    }

    public function store(StoreMemberRequest $request): JsonResponse
    {
        $company = $this->currentCompany($request);
        $data = $request->validated();

        $user = User::query()->firstOrCreate(
            ['email' => $data['email']],
            [
                'name' => $data['name'],
                'password' => $data['password'],
                'email_verified_at' => now(),
            ]
        );

        if ($company->users()->whereKey($user->id)->exists()) {
            return ApiResponse::error('User is already a member of this company', 422);
        }

        $company->users()->attach($user->id, [
            'role' => $data['role'],
            'joined_at' => now(),
        ]);

        $user->assignRole($data['role'] === 'admin' ? 'company-admin' : 'company-member');

        $member = $company->users()->whereKey($user->id)->firstOrFail();

        return ApiResponse::success(
            new MemberResource($member),
            'Member added successfully',
            201
        );
    }

    public function update(UpdateMemberRoleRequest $request, int $member): JsonResponse
    {
        $company = $this->currentCompany($request);
        $data = $request->validated();
        $target = $company->users()->whereKey($member)->first();

        if (! $target) {
            return ApiResponse::error('Member not found', 404);
        }

        if ($target->pivot->role === 'owner') {
            return ApiResponse::error('Owner role cannot be changed', 422);
        }

        $company->users()->updateExistingPivot($target->id, [
            'role' => $data['role'],
        ]);

        $target->syncRoles([$data['role'] === 'admin' ? 'company-admin' : 'company-member']);

        return ApiResponse::success(
            new MemberResource($company->users()->whereKey($target->id)->firstOrFail()),
            'Member role updated successfully'
        );
    }

    public function destroy(Request $request, int $member): JsonResponse
    {
        $company = $this->currentCompany($request);
        $target = $company->users()->whereKey($member)->first();

        if (! $target) {
            return ApiResponse::error('Member not found', 404);
        }

        if ($target->pivot->role === 'owner') {
            return ApiResponse::error('Owner cannot be removed', 422);
        }

        $company->users()->detach($target->id);

        return ApiResponse::success(null, 'Member removed successfully');
    }

    private function currentCompany(Request $request): Company
    {
        return $request->attributes->get('currentCompany');
    }
}
