<?php

namespace Modules\Account\Services;

use Illuminate\Http\Request;
use Modules\Account\Models\Family;
use Modules\Account\Models\FamilyMember;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class FamilyService
{
    /**
     * 获取家庭信息
     */
    public function getInfo(Request $request)
    {
        $userId = auth('api')->user()['uid'];

        $familyMember = FamilyMember::where('user_id', $userId)->first();

        if (!$familyMember) {
            return null;
        }

        $family = Family::with(['owner:uid,nickname,username', 'members:uid,nickname,username,email'])
            ->findOrFail($familyMember->family_id);

        return [
            'id' => $family->id,
            'name' => $family->name,
            'invite_code' => $family->invite_code,
            'owner_id' => $family->owner_id,
            'is_owner' => $family->owner_id == $userId,
            'created_at' => $family->created_at->format('Y-m-d H:i:s'),
            'owner' => $family->owner,
            'members' => $family->members
        ];
    }

    /**
     * 创建家庭
     */
    public function create(Request $request)
    {
        $userId = auth('api')->user()['uid'];

        // 检查是否已加入家庭
        $existingFamily = FamilyMember::where('user_id', $userId)->first();
        if ($existingFamily) {
            throw new \Exception('您已加入其他家庭，请先退出');
        }

        $data = $request->validate([
            'name' => 'required|string|max:50'
        ]);

        DB::beginTransaction();
        try {
            // 生成10位邀请码
            do {
                $inviteCode = strtoupper(substr(str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 10));
            } while (Family::where('invite_code', $inviteCode)->exists());

            $family = Family::create([
                'name' => $data['name'],
                'owner_id' => $userId,
                'invite_code' => $inviteCode
            ]);

            // 家主自动加入家庭
            FamilyMember::create([
                'family_id' => $family->id,
                'user_id' => $userId
            ]);

            DB::commit();

            return $family;
        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }

    /**
     * 加入家庭
     */
    public function join(Request $request)
    {
        $userId = auth('api')->user()['uid'];

        // 检查是否已加入家庭
        $existingFamily = FamilyMember::where('user_id', $userId)->first();
        if ($existingFamily) {
            throw new \Exception('您已加入其他家庭');
        }

        $data = $request->validate([
            'invite_code' => 'required|string|size:10'
        ]);

        $family = Family::where('invite_code', strtoupper($data['invite_code']))->first();

        if (!$family) {
            throw new \Exception('邀请码不存在');
        }

        // 检查是否是家主
        if ($family->owner_id == $userId) {
            throw new \Exception('您已经是该家庭的家主');
        }

        // 加入家庭
        FamilyMember::create([
            'family_id' => $family->id,
            'user_id' => $userId
        ]);

        return $family;
    }

    /**
     * 退出家庭
     */
    public function leave(Request $request)
    {
        $userId = auth('api')->user()['uid'];

        $familyMember = FamilyMember::where('user_id', $userId)->first();

        if (!$familyMember) {
            throw new \Exception('您还未加入任何家庭');
        }

        $family = Family::findOrFail($familyMember->family_id);

        // 家主不能退出，只能转让或删除
        if ($family->owner_id == $userId) {
            throw new \Exception('家主不能退出家庭，请先转让家主');
        }

        $familyMember->delete();

        return ['message' => '已退出家庭'];
    }

    /**
     * 获取家庭邀请码
     */
    public function getInviteCode(Request $request)
    {
        $userId = auth('api')->user()['uid'];

        $familyMember = FamilyMember::where('user_id', $userId)->first();

        if (!$familyMember) {
            throw new \Exception('您还未加入任何家庭');
        }

        $family = Family::findOrFail($familyMember->family_id);

        return [
            'invite_code' => $family->invite_code,
            'family_name' => $family->name
        ];
    }

    /**
     * 重新生成邀请码
     */
    public function regenerateInviteCode(Request $request)
    {
        $userId = auth('api')->user()['uid'];

        $familyMember = FamilyMember::where('user_id', $userId)->first();

        if (!$familyMember) {
            throw new \Exception('您还未加入任何家庭');
        }

        $family = Family::findOrFail($familyMember->family_id);

        // 只有家主可以重新生成邀请码
        if ($family->owner_id != $userId) {
            throw new \Exception('只有家主可以重新生成邀请码');
        }

        // 生成新邀请码
        do {
            $inviteCode = strtoupper(substr(str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 10));
        } while (Family::where('invite_code', $inviteCode)->exists());

        $family->update(['invite_code' => $inviteCode]);

        return [
            'invite_code' => $inviteCode,
            'family_name' => $family->name
        ];
    }

    /**
     * 移除家庭成员
     */
    public function removeMember(Request $request)
    {
        $userId = auth('api')->user()['uid'];

        $data = $request->validate([
            'user_id' => 'required|integer'
        ]);

        $familyMember = FamilyMember::where('user_id', $userId)->first();

        if (!$familyMember) {
            throw new \Exception('您还未加入任何家庭');
        }

        $family = Family::findOrFail($familyMember->family_id);

        // 只有家主可以移除成员
        if ($family->owner_id != $userId) {
            throw new \Exception('只有家主可以移除成员');
        }

        // 不能移除家主
        if ($family->owner_id == $data['user_id']) {
            throw new \Exception('不能移除家主');
        }

        // 移除成员
        $targetMember = FamilyMember::where('family_id', $family->id)
            ->where('user_id', $data['user_id'])
            ->first();

        if (!$targetMember) {
            throw new \Exception('该用户不在家庭中');
        }

        $targetMember->delete();

        return ['message' => '成员已移除'];
    }

    /**
     * 获取家庭成员列表
     */
    public function getMembers(Request $request)
    {
        $userId = auth('api')->user()['uid'];

        $familyMember = FamilyMember::where('user_id', $userId)->first();

        if (!$familyMember) {
            throw new \Exception('您还未加入任何家庭');
        }

        $family = Family::findOrFail($familyMember->family_id);

        $members = FamilyMember::with('user:uid,nickname,username,email')
            ->where('family_id', $family->id)
            ->get();

        return $members->map(function($member) use ($family) {
            return [
                'id' => $member->user->uid,
                'name' => $member->user->nickname,
                'username' => $member->user->username,
                'is_owner' => $family->owner_id == $member->user->uid
            ];
        })->toArray();
    }

    /**
     * 转让家主
     */
    public function transferOwner(Request $request)
    {
        $userId = auth('api')->user()['uid'];

        $data = $request->validate([
            'user_id' => 'required|integer'
        ]);

        $familyMember = FamilyMember::where('user_id', $userId)->first();

        if (!$familyMember) {
            throw new \Exception('您还未加入任何家庭');
        }

        $family = Family::findOrFail($familyMember->family_id);

        // 只有当前家主可以转让
        if ($family->owner_id != $userId) {
            throw new \Exception('只有家主可以转让');
        }

        // 目标用户必须在家庭中
        $targetMember = FamilyMember::where('family_id', $family->id)
            ->where('user_id', $data['user_id'])
            ->first();

        if (!$targetMember) {
            throw new \Exception('该用户不在家庭中');
        }

        // 转让家主
        $family->update(['owner_id' => $data['user_id']]);

        return ['message' => '家主已转让'];
    }
}
