import { z } from "zod";
import { api } from "./client";

export const AuthRequestSchema = z.union([
  z.object({ status: z.literal("code_sent"), channel: z.string() }),
  z.object({ status: z.literal("onboarding"), deep_links: z.object({ tg: z.string(), max: z.string() }) }),
]);
export type AuthRequest = z.infer<typeof AuthRequestSchema>;

export const VerifySchema = z.object({ token: z.string(), driver_id: z.number() });
export const BalanceSchema = z.object({
  accounts: z.array(z.object({ bucket: z.string(), balance: z.number() })),
});
export const TopupSchema = z.object({
  order_id: z.string(), pay_url: z.string(), commission: z.number(), total: z.number(),
});
export const PaymentStateSchema = z.object({ order_id: z.string(), status: z.string() });
export const PaymentsSchema = z.object({
  payments: z.array(z.object({
    order_id: z.string(), bucket: z.string(), amount: z.number(), commission: z.number(),
    method: z.string(), status: z.string(),
    created_at: z.string().nullable(), paid_at: z.string().nullable(),
  })),
});

export const authRequest = async (phone: string) =>
  AuthRequestSchema.parse(await api.post("driver/auth/request", { json: { phone } }).json());
export const authVerify = async (phone: string, code: string) =>
  VerifySchema.parse(await api.post("driver/auth/verify", { json: { phone, code } }).json());
export const getBalance = async () =>
  BalanceSchema.parse(await api.get("driver/balance").json());
export const topup = async (bucket: string, amount: number, method: "qr" | "card") =>
  TopupSchema.parse(await api.post("driver/topup", { json: { bucket, amount, method } }).json());
export const getPaymentState = async (orderId: string) =>
  PaymentStateSchema.parse(await api.get(`driver/payment/${orderId}`).json());
export const getPayments = async () =>
  PaymentsSchema.parse(await api.get("driver/payments").json());
