import { z } from 'zod';
import * as companiesRepo from '../repositories/companies.repository.js';
import * as ridesRepo from '../repositories/rides.repository.js';

// Validation schemas
export const syncCompaniesSchema = z.object({
  companies: z.array(
    z.object({
      id: z.string(),
      name: z.string(),
      cost_per_km: z.number().or(z.string()),
      notes: z.string().optional(),
    })
  ),
});

export const syncRidesSchema = z.object({
  rides: z.array(
    z.object({
      id: z.string(),
      user_id: z.string(),
      company: z.string(),
      km: z.number().or(z.string()),
      cost_per_km: z.number().or(z.string()),
      total: z.number().or(z.string()),
      ride_date: z.string(),
      synced: z.number().optional(),
    })
  ),
});

export async function syncCompanies(
  input: z.infer<typeof syncCompaniesSchema>
) {
  const synced = [];
  for (const company of input.companies) {
    const result = await companiesRepo.upsertCompany({
      id: company.id,
      name: company.name,
      cost_per_km: company.cost_per_km,
      notes: company.notes,
    });
    synced.push(result);
  }
  return synced;
}

export async function syncRides(
  input: z.infer<typeof syncRidesSchema>
) {
  const synced = [];
  for (const ride of input.rides) {
    const result = await ridesRepo.upsertRide({
      id: ride.id,
      user_id: ride.user_id,
      company: ride.company,
      km: ride.km,
      cost_per_km: ride.cost_per_km,
      total: ride.total,
      ride_date: ride.ride_date,
      synced: ride.synced,
    });
    synced.push(result);
  }
  return synced;
}

export async function getAllCompanies() {
  return companiesRepo.listCompanies();
}

export async function getAllRides() {
  return ridesRepo.listAllRides();
}
