<?php

namespace App\Services;

use App\Models\Society;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class SocietyService
{
    /**
     * Create a new society with transaction safety.
     */
    public function createSociety(array $data)
    {
        return DB::transaction(function () use ($data) {
            return Society::create($data);
        });
    }

    /**
     * Add a user to a society with validation and transaction safety.
     */
    public function addUserToSociety(int $societyId, array $userData)
    {
        return DB::transaction(function () use ($societyId, $userData) {
            $userData['society_id'] = $societyId;
            $userData['password'] = Hash::make($userData['password']);

            return User::create($userData);
        });
    }

    /**
     * Update society with integrity checks.
     */
    public function updateSociety(int $id, array $data)
    {
        $society = Society::findOrFail($id);
        $society->update($data);
        return $society;
    }

    /**
     * Delete society and perform necessary cleanup.
     */
    public function deleteSociety(int $id)
    {
        return DB::transaction(function () use ($id) {
            $society = Society::findOrFail($id);
            // Additional cleanup logic can go here (e.g. archiving data)
            return $society->delete();
        });
    }

    /**
     * Delete user from society with integrity check and transaction safety.
     */
    public function deleteUserFromSociety(int $societyId, int $userId)
    {
        return DB::transaction(function () use ($societyId, $userId) {
            $user = User::where('society_id', $societyId)->findOrFail($userId);
            return $user->delete();
        });
    }

    /**
     * Update user details with validation and transaction safety.
     */
    public function updateUserInSociety(int $societyId, int $userId, array $data)
    {
        return DB::transaction(function () use ($societyId, $userId, $data) {
            $user = User::where('society_id', $societyId)->findOrFail($userId);

            if (isset($data['password'])) {
                $data['password'] = Hash::make($data['password']);
            } else {
                unset($data['password']); // Don't overwrite with null
            }

            $user->update($data);
            return $user;
        });
    }
}
