// API Route: /api/customers
// Handles CRUD operations for customers

import { NextApiRequest, NextApiResponse } from 'next';
import { customerService, customerServiceExtended } from '@/lib/database/mysql-service';
import { withAuth } from '@/lib/middleware/auth';
import { withErrorHandler } from '@/lib/middleware/error-handler';
import { validateRequest } from '@/lib/middleware/validation';
import { z } from 'zod';

// Validation schemas
const createCustomerSchema = z.object({
  name: z.string().min(2, 'Name must be at least 2 characters'),
  phone: z.string().min(10, 'Phone must be at least 10 digits'),
  email: z.string().email().optional(),
  address: z.string().optional(),
  notes: z.string().optional(),
});

const updateCustomerSchema = createCustomerSchema.partial();

const querySchema = z.object({
  page: z.string().optional().transform(val => val ? parseInt(val) : 1),
  limit: z.string().optional().transform(val => val ? parseInt(val) : 10),
  search: z.string().optional(),
  orderBy: z.string().optional().default('created_at'),
  orderDirection: z.enum(['ASC', 'DESC']).optional().default('DESC'),
});

async function handler(req: NextApiRequest, res: NextApiResponse) {
  const { method } = req;
  const { user, shopId } = req as any; // Added by auth middleware

  switch (method) {
    case 'GET':
      return handleGet(req, res, shopId);
    case 'POST':
      return handlePost(req, res, shopId, user.id);
    default:
      res.setHeader('Allow', ['GET', 'POST']);
      return res.status(405).json({ error: `Method ${method} not allowed` });
  }
}

async function handleGet(req: NextApiRequest, res: NextApiResponse, shopId: number) {
  const query = querySchema.parse(req.query);
  
  try {
    if (query.search) {
      // Search customers
      const customers = await customerServiceExtended.searchCustomers(query.search, shopId);
      return res.status(200).json({
        success: true,
        data: customers,
        total: customers.length,
        page: 1,
        limit: customers.length,
        totalPages: 1,
      });
    } else {
      // Get all customers with pagination
      const result = await customerService.findByShop(shopId, {
        page: query.page,
        limit: query.limit,
        orderBy: query.orderBy,
        orderDirection: query.orderDirection,
      });
      
      return res.status(200).json({
        success: true,
        ...result,
      });
    }
  } catch (error: any) {
    console.error('Error fetching customers:', error);
    return res.status(500).json({
      success: false,
      error: 'Failed to fetch customers',
      details: error.message,
    });
  }
}

async function handlePost(req: NextApiRequest, res: NextApiResponse, shopId: number, userId: number) {
  try {
    const validatedData = createCustomerSchema.parse(req.body);
    
    const customer = await customerService.create({
      ...validatedData,
      shop_id: shopId,
      total_orders: 0,
      total_spent: 0,
    });
    
    return res.status(201).json({
      success: true,
      data: customer,
      message: 'Customer created successfully',
    });
  } catch (error: any) {
    if (error.name === 'ZodError') {
      return res.status(400).json({
        success: false,
        error: 'Validation error',
        details: error.errors,
      });
    }
    
    console.error('Error creating customer:', error);
    return res.status(500).json({
      success: false,
      error: 'Failed to create customer',
      details: error.message,
    });
  }
}

export default withErrorHandler(withAuth(handler));
