<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\repository\user;

use app\model\UserAddress;
use app\repository\BaseRepository;


/**
 * Address Repository
 * @package app\repository\user
 */
class AddressRepository extends BaseRepository
{

    /**
     * 查询用户所有地址列表
     * @param int $userId 用户ID
     * @return array
     */
    public function listByUser(int $userId): array
    {
        return UserAddress::where('user_id', $userId)
            ->order('is_default', 'desc')
            ->order('id', 'desc')
            ->select()
            ->toArray();
    }


    /**
     * 按主键和用户ID查找地址
     * @param int $id 地址ID
     * @param int $userId 用户ID
     * @return UserAddress|null
     */
    public function findById(int $id, int $userId): ?UserAddress
    {
        $address = UserAddress::where('id', $id)->where('user_id', $userId)->find();
        return $address instanceof UserAddress ? $address : null;
    }


    /**
     * 查找默认地址
     * @param int $userId
     * @return UserAddress|null
     */
    public function findDefault(int $userId): ?UserAddress
    {
        $address = UserAddress::where('user_id', $userId)->where('is_default', 1)->find();
        return $address instanceof UserAddress ? $address : null;
    }


    /**
     * 统计用户地址数量
     * @param int $userId 用户ID
     * @return int
     */
    public function countByUser(int $userId): int
    {
        return UserAddress::where('user_id', $userId)->count();
    }


    /**
     * 取消用户所有默认地址
     * @param int $userId 用户ID
     * @return void
     */
    public function unsetDefault(int $userId): void
    {
        UserAddress::where('user_id', $userId)->where('is_default', 1)->update(['is_default' => 0]);
    }


    /**
     * 创建地址记录
     * @param array $data
     * @return UserAddress
     */
    public function create(array $data): UserAddress
    {
        return UserAddress::create($data);
    }


    /**
     * 更新地址记录
     * @param UserAddress $address
     * @param array $data
     * @return bool
     */
    public function update(UserAddress $address, array $data): bool
    {
        return $address->save($data);
    }


    /**
     * 删除地址记录
     * @param UserAddress $address
     * @return bool
     */
    public function delete(UserAddress $address): bool
    {
        return $address->delete();
    }
}