import { getClient, getCurrentUserId } from "./_client";
import type { Trip, TripInsert, TripUpdate } from "./schema";
export const trips = {
/** List all trips for the current user */
async list(filters?: { status?: string; vehicleId?: string }) {
const userId = await getCurrentUserId();
let query = getClient()
.from("trips")
.select("*")
.eq("user_id", userId)
.order("trip_end", { ascending: false });
if (filters?.status) {
query = query.eq("status", filters.status);
}
if (filters?.vehicleId) {
query = query.eq("vehicle_id", filters.vehicleId);
}
const { data, error } = await query;
if (error) throw error;
return data as Trip[];
},
/** Get a single trip by ID */
async get(id: string) {
const userId = await getCurrentUserId();
const { data, error } = await getClient()
.from("trips")
.select("*")
.eq("id", id)
.eq("user_id", userId)
.single();
if (error) throw error;
return data as Trip;
},
/** Create a new trip */
async create(trip: TripInsert) {
const userId = await getCurrentUserId();
const { data, error } = await getClient()
.from("trips")
.insert({ ...trip, user_id: userId })
.select()
.single();
if (error) throw error;
return data as Trip;
},
/** Update an existing trip */
async update(id: string, updates: TripUpdate) {
const userId = await getCurrentUserId();
const { data, error } = await getClient()
.from("trips")
.update(updates)
.eq("id", id)
.eq("user_id", userId)
.select()
.single();
if (error) throw error;
return data as Trip;
},
/** Delete a trip */
async delete(id: string) {
const userId = await getCurrentUserId();
const { error } = await getClient()
.from("trips")
.delete()
.eq("id", id)
.eq("user_id", userId);
if (error) throw error;
},
};