import { api } from '@/api/index'
import type { TbGuestDTO } from '@/types/sys/guest'
import type { LoginParam, LoginDomain } from '@/types/auth/auth'
import type { ResultDomain, PageRequest } from '@/types'

/**
 * 来客 API
 * 通过 Gateway (8180) 访问 System Service
 * 路由规则：/urban-lifeline/system/** → system-service
 */
export const guestAPI = {
    baseUrl: '/urban-lifeline/system/guest',

    /**
     * 创建来客
     */
    async createGuest(guest: TbGuestDTO): Promise<ResultDomain<TbGuestDTO>> {
        const response = await api.post<TbGuestDTO>(`${this.baseUrl}`, guest)
        return response.data
    },

    /**
     * 更新来客
     */
    async updateGuest(guest: TbGuestDTO): Promise<ResultDomain<TbGuestDTO>> {
        const response = await api.put<TbGuestDTO>(`${this.baseUrl}`, guest)
        return response.data
    },

    /**
     * 删除来客
     */
    async deleteGuest(userId: string): Promise<ResultDomain<TbGuestDTO>> {
        const response = await api.delete<TbGuestDTO>(`${this.baseUrl}`, { params: { userId } })
        return response.data
    },

    /**
     * 根据微信ID查询来客
     */
    async selectGuestByWechat(wechatId: string): Promise<ResultDomain<TbGuestDTO>> {
        const response = await api.get<TbGuestDTO>(`${this.baseUrl}/wechat/${wechatId}`)
        return response.data
    },

    /**
     * 获取来客列表
     */
    async listGuest(filter?: TbGuestDTO): Promise<ResultDomain<TbGuestDTO>> {
        const response = await api.get<TbGuestDTO>(`${this.baseUrl}/list`, { params: filter })
        return response.data
    },

    /**
     * 分页查询来客
     */
    async pageGuest(pageRequest: PageRequest<TbGuestDTO>): Promise<ResultDomain<TbGuestDTO>> {
        const response = await api.post<TbGuestDTO>(`${this.baseUrl}/page`, pageRequest)
        return response.data
    },

    /**
     * 微信小程序用户识别登录
     * 优先尝试员工登录，失败则自动注册/查询来客
     * @param loginParam 登录参数（wechatId或phone必填）
     * @returns LoginDomain 包含用户信息和token
     */
    async identify(loginParam: LoginParam): Promise<ResultDomain<LoginDomain>> {
        const response = await api.post<LoginDomain>(`${this.baseUrl}/identify`, loginParam)
        return response.data
    }
}
