import { API_BASE_URL, Note } from '../types'

export const noteService = {
    // すべてのノートを取得（オプションでグループによるフィルタリングが可能）
    getAll: async (token: string, groupId?: string, categoryId?: string): Promise<Note[]> => {
        const url = new URL(`${API_BASE_URL}/notes`, window.location.origin)
        if (groupId) {
            url.searchParams.append('groupId', groupId)
        }
        if (categoryId) {
            url.searchParams.append('categoryId', categoryId)
        }
        const response = await fetch(url.toString(), {
            headers: {
                Authorization: `Bearer ${token}`
            }
        })
        if (!response.ok) {
            throw new Error(`Failed to fetch notes: ${response.status} ${response.statusText}`)
        }
        return response.json()
    },

    // ノートを作成
    create: async (token: string, data: { title: string, content: string, groupId: string, categoryId?: string }): Promise<Note> => {
        const response = await fetch(`${API_BASE_URL}/notes`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${token}`
            },
            body: JSON.stringify(data)
        })
        if (!response.ok) {
            throw new Error('Failed to create note')
        }
        return response.json()
    },

    // ノートを更新
    update: async (token: string, id: string, data: { title?: string, content?: string, categoryId?: string }): Promise<Note> => {
        const response = await fetch(`${API_BASE_URL}/notes/${id}`, {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${token}`
            },
            body: JSON.stringify(data)
        })
        if (!response.ok) {
            throw new Error('Failed to update note')
        }
        return response.json()
    },

    // ノートを削除
    delete: async (token: string, id: string): Promise<void> => {
        const response = await fetch(`${API_BASE_URL}/notes/${id}`, {
            method: 'DELETE',
            headers: {
                Authorization: `Bearer ${token}`
            }
        })
        if (!response.ok) {
            throw new Error('Failed to delete note')
        }
    },

    // ノートを知識ベースにインデックス（ベクトル化）
    createFromPDFSelection: async (
        token: string,
        fileId: string,
        screenshot: Blob,
        groupId?: string,
        pageNumber?: number,
    ): Promise<Note> => {
        const formData = new FormData()
        formData.append('screenshot', screenshot, 'selection.png')
        formData.append('fileId', fileId)
        if (groupId) {
            formData.append('groupId', groupId)
        }
        if (pageNumber !== undefined) {
            formData.append('pageNumber', pageNumber.toString())
        }

        const response = await fetch(`${API_BASE_URL}/notes/from-pdf-selection`, {
            method: 'POST',
            headers: {
                Authorization: `Bearer ${token}`
            },
            body: formData
        })
        if (!response.ok) {
            throw new Error('Failed to create note from PDF selection')
        }
        return response.json()
    }
}
