import { useInfiniteQuery, useQuery } from '@tanstack/react-query' import { useState } from 'react' import { listMyTalksInfiniteOptions, listMyTalksOptions, listTalksInfiniteOptions, talkGroupsOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen' import { TalkTopic, type TalkData } from '@nalssigak/shared/api/client/types.gen' import { kst } from '@nalssigak/shared/lib' import { useRegion } from './regionContext' // 글 주제와 피드 묶음 이름 export const TOPICS = [ [TalkTopic.LOCAL, '동네 이야기'], [TalkTopic.SKY, '하늘·노을'], [TalkTopic.RAIN, '비·눈'], [TalkTopic.FOLIAGE, '단풍·꽃'], [TalkTopic.OUTFIT, '오늘 옷차림'], ] as const export const topicName = (t?: number) => TOPICS.find(([k]) => k === t)?.[1] ?? '동네 이야기' /** 오늘 피드 묶음: 0 은 '동네 사람들', 나머지는 주제별(3장 이상일 때만 옴) */ export function useTalkGroups() { const { region } = useRegion() const q = useQuery(talkGroupsOptions({ query: { region: region.code } })) const groups = new Map((q.data?.groups ?? []).map((g) => [g.topic, g.talks ?? []])) return { groups, loaded: q.isSuccess } } /** 주제별 글 페이지 목록 (topic 없으면 전체) */ export function useTopicTalks(topic?: TalkTopic) { const { region } = useRegion() const list = useInfiniteQuery({ ...listTalksInfiniteOptions({ query: { region: region.code, ...(topic ? { topic } : {}) } }), initialPageParam: {}, getNextPageParam: (last) => last.next_cursor ?? undefined, }) return { talks: list.data?.pages.flatMap((p) => p.talks ?? []) ?? [], loaded: list.isSuccess, more: list.hasNextPage && !list.isFetchingNextPage, loadMore: list.fetchNextPage, } } /** 오늘(한국 날짜) 쓴 내 글, 최신순. 로그인했을 때만 받는다 */ export function useTodayMyTalks(loggedIn: boolean) { const q = useQuery({ ...listMyTalksOptions(), enabled: loggedIn }) // 오늘 날짜는 화면을 연 때 기준으로 한 번만 const [now] = useState(() => kst(new Date())) return (q.data?.talks ?? []).filter((t) => { const d = kst(t.created_at) return d.y === now.y && d.mo === now.mo && d.d === now.d }) } /** 내가 쓴 글 (최신순) */ export function useMyTalks(enabled = true) { const list = useInfiniteQuery({ ...listMyTalksInfiniteOptions(), enabled, initialPageParam: {}, getNextPageParam: (last) => last.next_cursor ?? undefined, }) return { talks: list.data?.pages.flatMap((p) => p.talks ?? []) ?? [], loaded: list.isSuccess, more: list.hasNextPage && !list.isFetchingNextPage, loadMore: list.fetchNextPage, } }