const axios = require('axios')
const env = require('../config/env')
const AppError = require('../utils/appError')

function getHeaders() {
    const headers = {
        'Content-Type': 'application/json',
    }

    if (env.pocketbaseAuthToken) {
        headers.Authorization = env.pocketbaseAuthToken.startsWith('Bearer ')
            ? env.pocketbaseAuthToken
            : `Bearer ${env.pocketbaseAuthToken}`
    }

    return headers
}

function buildUrl(path) {
    const base = env.pocketbaseUrl.replace(/\/+$/, '')
    const normalizedPath = path.replace(/^\/+/, '')
    return `${base}/${normalizedPath}`
}

async function request(config) {
    try {
        const response = await axios({
            timeout: 10000,
            headers: getHeaders(),
            ...config,
        })
        return response.data
    } catch (error) {
        const detail = error.response?.data || error.message
        throw new AppError('PocketBase 数据操作失败', 500, {
            detail,
        })
    }
}

async function listUsersByFilter(filter) {
    const data = await request({
        method: 'get',
        url: buildUrl('collections/tbl_users/records'),
        params: {
            filter,
            perPage: 1,
        },
    })

    return data.items || []
}

async function createUser(payload) {
    return request({
        method: 'post',
        url: buildUrl('collections/tbl_users/records'),
        data: payload,
    })
}

async function updateUser(recordId, payload) {
    return request({
        method: 'patch',
        url: buildUrl(`collections/tbl_users/records/${recordId}`),
        data: payload,
    })
}

async function getCompanyByCompanyId(companyId) {
    if (!companyId) return null

    const data = await request({
        method: 'get',
        url: buildUrl('collections/tbl_company/records'),
        params: {
            filter: `company_id = "${companyId}"`,
            perPage: 1,
        },
    })

    return data.items?.[0] || null
}

module.exports = {
    listUsersByFilter,
    createUser,
    updateUser,
    getCompanyByCompanyId,
}
