import { Request, Response } from 'express';
import * as syncService from '../services/sync.service.js';

export async function syncCompanies(req: Request, res: Response): Promise<void> {
  try {
    const parsed = syncService.syncCompaniesSchema.safeParse(req.body);
    if (!parsed.success) {
      res.status(400).json({ error: parsed.error.flatten() });
      return;
    }

    const synced = await syncService.syncCompanies(parsed.data);
    res.json({
      success: true,
      message: `${synced.length} company/companies synced`,
      data: synced,
    });
  } catch (err: any) {
    res.status(500).json({ error: err.message ?? 'Error syncing companies' });
  }
}

export async function syncRides(req: Request, res: Response): Promise<void> {
  try {
    const parsed = syncService.syncRidesSchema.safeParse(req.body);
    if (!parsed.success) {
      res.status(400).json({ error: parsed.error.flatten() });
      return;
    }

    const synced = await syncService.syncRides(parsed.data);
    res.json({
      success: true,
      message: `${synced.length} ride(s) synced`,
      data: synced,
    });
  } catch (err: any) {
    res.status(500).json({ error: err.message ?? 'Error syncing rides' });
  }
}

export async function getCompanies(req: Request, res: Response): Promise<void> {
  try {
    const companies = await syncService.getAllCompanies();
    res.json({
      success: true,
      data: companies,
    });
  } catch (err: any) {
    res.status(500).json({ error: err.message ?? 'Error fetching companies' });
  }
}

export async function getRides(req: Request, res: Response): Promise<void> {
  try {
    const rides = await syncService.getAllRides();
    res.json({
      success: true,
      data: rides,
    });
  } catch (err: any) {
    res.status(500).json({ error: err.message ?? 'Error fetching rides' });
  }
}
