Files
k-tv/k-tv-frontend/hooks/use-import-channel.ts

54 lines
1.6 KiB
TypeScript

"use client";
import { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { api } from "@/lib/api";
import type { ChannelImportData } from "@/app/(main)/dashboard/components/import-channel-dialog";
import { WEEKDAYS } from "@/lib/types";
import type { Weekday } from "@/lib/types";
export function useImportChannel(token: string | null) {
const queryClient = useQueryClient();
const [isPending, setIsPending] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleImport = async (data: ChannelImportData) => {
if (!token) return;
setIsPending(true);
setError(null);
try {
const created = await api.channels.create(
{
name: data.name,
timezone: data.timezone,
description: data.description,
},
token,
);
await api.channels.update(
created.id,
{
schedule_config: {
day_blocks: Object.fromEntries(
WEEKDAYS.map(d => [d, d === 'monday' ? data.blocks : []])
) as Record<Weekday, typeof data.blocks>,
},
recycle_policy: data.recycle_policy,
},
token,
);
await queryClient.invalidateQueries({ queryKey: ["channels"] });
return true; // success signal for closing dialog
} catch (e) {
setError(e instanceof Error ? e.message : "Import failed");
return false;
} finally {
setIsPending(false);
}
};
const clearError = () => setError(null);
return { handleImport, isPending, error, clearError };
}