import { query } from "../_generated/server";
import { v } from "convex/values";

export const listByOrg = query({
  args: {
    organizationId: v.string(),
    includeInactive: v.optional(v.boolean()),
  },
  handler: async (ctx, { organizationId, includeInactive }) => {
    return ctx.db
      .query("vehicles")
      .withIndex("by_organizationId_isActive", (q) =>
        includeInactive
          ? q.eq("organizationId", organizationId)
          : q.eq("organizationId", organizationId).eq("isActive", true),
      )
      .order("desc")
      .collect();
  },
});

export const getById = query({
  args: { id: v.id("vehicles") },
  handler: async (ctx, { id }) => ctx.db.get(id),
});

export const listRentalsByOrg = query({
  args: {
    organizationId: v.string(),
    status: v.optional(v.string()),
  },
  handler: async (ctx, { organizationId, status }) => {
    const results = await ctx.db
      .query("vehicle_rentals")
      .withIndex("by_organizationId_status", (q) => {
        const base = q.eq("organizationId", organizationId);
        return status ? base.eq("status", status as never) : base;
      })
      .order("desc")
      .collect();

    return Promise.all(
      results.map(async (r) => ({
        ...r,
        vehicle: await ctx.db.get(r.vehicleId as never),
      })),
    );
  },
});

export const getRentalById = query({
  args: { id: v.id("vehicle_rentals") },
  handler: async (ctx, { id }) => {
    const rental = await ctx.db.get(id);
    if (!rental) return null;
    return { ...rental, vehicle: await ctx.db.get(rental.vehicleId as never) };
  },
});
