/**
 * Bots API client
 * @since 1.1.0
 */

import { apiClient } from './client'
import type { BotFormData, BotResponse, BotsListResponse, BotStatsResponse } from '@/types/bot'

function normalizeHexColorTo6(value: unknown): unknown {
    if (typeof value !== 'string') return value
    const v = value.trim()
    if (!v) return value
    const m = v.match(/^#([0-9a-fA-F]{3})$/)
    if (!m) return v
    const [r, g, b] = m[1].split('')
    return `#${r}${r}${g}${g}${b}${b}`
}

function normalizeBotPosition(value: unknown): unknown {
    if (typeof value !== 'string') return value
    const v = value.trim()
    if (!v) return value
    // Backend expects one of: bottom-right, bottom-left, top-right, top-left
    // Some legacy records may have underscores.
    const normalized = v.toLowerCase().replace(/_/g, '-')
    const allowed = new Set(['bottom-right', 'bottom-left', 'top-right', 'top-left'])
    return allowed.has(normalized) ? normalized : value
}

function normalizeBotPayload(data: Partial<BotFormData>): Partial<BotFormData> {
    // Backend validation currently requires `primary_color` to be exactly "#RRGGBB" (not "#RGB").
    // Normalize on the client to prevent intermittent 400s depending on stored data.
    // Only inject normalized keys when they are actually present in the payload to
    // avoid sending undefined / null values for lightweight partial updates.
    const out: Partial<BotFormData> = { ...data }
    if ('primary_color' in data) {
        (out as any).primary_color = normalizeHexColorTo6((data as any).primary_color)
    }
    if ('position' in data) {
        (out as any).position = normalizeBotPosition((data as any).position)
    }
    return out
}

export const botsApi = {
    /**
     * Get all bots
     */
    async getBots(page = 1, perPage = 50, language?: string): Promise<BotsListResponse> {
        return apiClient.get('bots', { page, per_page: perPage, language })
    },

    /**
     * Get a single bot by ID
     */
    async getBot(id: number): Promise<BotResponse> {
        return apiClient.get(`bots/${id}`)
    },

    /**
     * Create a new bot
     */
    async createBot(data: Partial<BotFormData>): Promise<BotResponse> {
        return apiClient.post('bots', normalizeBotPayload(data))
    },

    /**
     * Update an existing bot
     */
    async updateBot(id: number, data: Partial<BotFormData>): Promise<BotResponse> {
        return apiClient.put(`bots/${id}`, normalizeBotPayload(data))
    },

    /**
     * Delete a bot
     */
    async deleteBot(id: number): Promise<{ success: boolean; data: { message: string } }> {
        return apiClient.delete(`bots/${id}`)
    },

    /**
     * Duplicate a bot
     */
    async duplicateBot(id: number): Promise<BotResponse> {
        return apiClient.post(`bots/${id}/duplicate`)
    },

    /**
     * Set a bot as default
     */
    async setDefaultBot(id: number): Promise<{ success: boolean; data: { message: string } }> {
        return apiClient.put(`bots/${id}/default`)
    },

    /**
     * Get bot statistics
     */
    async getBotStats(): Promise<BotStatsResponse> {
        return apiClient.get('bots/stats')
    },

    /**
     * Get bots that override a given bot due to more specific display conditions
     */
    async getOverridingBots(id: number): Promise<OverridingBotsResponse> {
        return apiClient.get(`bots/${id}/overriding-bots`)
    },

    /**
     * Get bots that a given bot overrides due to its more specific display conditions
     */
    async getOverriddenBots(id: number): Promise<OverriddenBotsResponse> {
        return apiClient.get(`bots/${id}/overridden-bots`)
    },
}

/**
 * Response type for overriding bots API
 */
export interface OverridingBotsResponse {
    success: boolean
    data: {
        current_bot: {
            id: number
            bot_name: string
            scope: string
        }
        overriding_bots: Array<{
            id: number
            bot_name: string
            is_default: boolean
            overlapping_scopes: string[]
            conditions_summary: string
        }>
    }
}

/**
 * Response type for overridden bots API
 */
export interface OverriddenBotsResponse {
    success: boolean
    data: {
        current_bot: {
            id: number
            bot_name: string
            scope: string
        }
        overridden_bots: Array<{
            id: number
            bot_name: string
            is_default: boolean
            their_scope: string
            overlapping_scopes: string[]
        }>
    }
}

