<?php

namespace App\Managers;

use App\Exceptions\AlertException;
use App\Models\Deed\FriendsModel;
use App\Models\Friends\FriendModel;

class DeedFriendManager
{

    /**
     * 星标某好友
     * @param  int  $uid
     * @param  int  $friend_uid
     * @return bool
     * @throws AlertException
     */
    public function starFriend(int $uid, int $friend_uid)
    {
        $friend = FriendsModel::where([['uid', $uid], ['friend_uid', $friend_uid]])->first();
        if (!$friend) {
            throw new AlertException("非好友关系", 404);
        }
        if (0 == $friend->star_at) {
            $friend->star_at = time();
        } else {
            $friend->star_at = 0;
        }

        $friend->save();
        return true;
    }

    /**
     * 隐藏某好友
     * @param  int  $uid
     * @param  int  $friend_uid
     * @return bool
     * @throws AlertException
     */
    public function hideFriend(int $uid, int $friend_uid)
    {
        /** @var FriendModel|null $friend */
        $friend = FriendModel::where([['uid', $uid], ['friend_uid', $friend_uid]])->first();
        if (!$friend) {
            throw new AlertException("非好友关系", 404);
        }
        $friend->is_hide = 1;
        $friend->is_friend = 0;
        $friend->unfriend_at = time();
        /** @var FriendModel $other */
        $other = FriendModel::where([['uid', $friend_uid], ['friend_uid', $uid]])->first();
        $other->is_friend = 0;
        $other->is_hide = 1;
        $other->unfriend_at = time();
        $other->last_msg = "对方解除了与你的好友关系";
        $other->unread_cnt = $other->unread_cnt + 1;
        $friend->save();
        $other->save();
        return true;
    }
}
