const Joi = require("joi");

const zoneValidation = Joi.object({
  zoneName: Joi.string().min(3).required(),
  zoneAddress: Joi.object({
    address: Joi.string().required(),
    city: Joi.string().required(),
    state: Joi.string().required()
  }).required(),

  coordinates: Joi.array()
    .items(
      Joi.object({
        lat: Joi.number().required(),
        lng: Joi.number().required(),
      })
    )
    .min(3) // polygon must have at least 3 points
    .max(100) // allow up to 100 points for complex polygons
    .required(),

  // Extra fare rule is optional
  extraFareRule: Joi.object({
    fareType: Joi.string().valid('flat', 'percentage').required(),
    fareAmount: Joi.number().required(),
    reason: Joi.string().allow('', null),
  }).optional(),
  zoneAdmin: Joi.object({
    fullName: Joi.string().min(3).required(),
    email: Joi.string().email().required(),
    phone: Joi.string().min(10).max(15).required(),
    password: Joi.string().min(6).required(),
  }).required(),
  zoneContact: Joi.number().required()
});


// Vendor Document Schema
const vendorDocumentSchema = Joi.object({
  docType: Joi.string().valid('gst', 'pan', 'address-proof', 'business-license', 'bank-statement', 'insurance', 'other').required(),
  fileUrl: Joi.string().required()
});

// Vendor Account Details Schema
const vendorAccountDetailsSchema = Joi.object({
  accountHolderName: Joi.string().required(),
  accountNumber: Joi.string().required(),
  ifscCode: Joi.string().required(),
  bankName: Joi.string().required(),
  branchName: Joi.string().required(),
  upiId: Joi.string().required()
});

const vendorFinancialSchema = Joi.object({
  commissionType: Joi.string().valid('flat', 'percentage').required(),
  commissionAmount: Joi.number().required(),
  paymentCycle: Joi.string().valid('daily', 'weekly', 'monthly').required(),
  maximumPayoutThreshold: Joi.number().required(),
  taxDeduction: Joi.number().required(),
})

const vendorSchema = Joi.object({
  vendorName: Joi.string().min(3).required(),
  displayName: Joi.string().min(3).required(),
  email: Joi.string().email().required(),
  phone: Joi.string().min(10).max(15).required(),
  password: Joi.string().min(6).required(),
  operationalZone: Joi.string().required(),
  registeredAddress: Joi.string().required(),
  status: Joi.string().valid('Pending', 'Active', 'Inactive', 'Suspended', 'Rejected').optional(),

  // Documents validation
  documents: Joi.array().items(vendorDocumentSchema).optional(),

  // Account details validation
  accountDetails: vendorAccountDetailsSchema.optional(),

  // Financial details validation
  financialSummary: vendorFinancialSchema.optional()
});

const vehicleCategorySchema = Joi.object({
  categoryName: Joi.string().required(),
  defaultSeats: Joi.number().required(),
  description: Joi.string().allow('', null),
  status: Joi.string().valid('active', 'inactive').optional()
});

const vehicleGroupSchema = Joi.object({
  groupName: Joi.string().required(),
  category: Joi.string().required(), // ObjectId
  tier: Joi.string().required(),
  seats: Joi.string().required(),
  description: Joi.string().allow('', null),
  status: Joi.string().valid('active', 'inactive').optional(),
  // Fuel-wise pricing array
  fuelPricing: Joi.array().items(
    Joi.object({
      fuelType: Joi.string().valid('petrol', 'diesel', 'cng', 'electric').required(),
      bootSpace: Joi.string().valid('available', 'unavailable').optional(),
      roof: Joi.string().valid('available', 'unavailable').optional(),
      luggageCapacity: Joi.number().min(0).optional(),
      acBaseFare: Joi.number().min(0).optional(),
      nonAcBaseFare: Joi.number().min(0).optional(),
      baseKm: Joi.number().min(0).optional(),
      minFare: Joi.number().min(0).optional(),
      ratePerKmAc: Joi.number().min(0).optional(),
      ratePerKmNonAc: Joi.number().min(0).optional(),
      waitingCharge: Joi.number().min(0).optional()
    })
  ).optional(),

  // Rental pricing array
  rentalPricing: Joi.array().items(
    Joi.object({
      hours: Joi.number().required().min(1),
      baseKm: Joi.number().required().min(0),
      baseFare: Joi.number().required().min(0),
      extraFarePerKm: Joi.number().required().min(0),
      fuelType: Joi.string().valid('petrol', 'diesel', 'cng', 'electric').default('petrol')
    })
  ).optional(),

  // Night charge settings
  nightChargeType: Joi.string().valid('percentage', 'fixed').optional(),
  nightChargeValue: Joi.number().min(0).optional(),
  nightStartTime: Joi.string().pattern(/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/).optional(), // HH:mm format
  nightEndTime: Joi.string().pattern(/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/).optional(),   // HH:mm format

  // Cancellation policy
  cancellationPolicy: Joi.string().allow('', null).optional(),

  // Vehicle images
  vehicleImages: Joi.object({
    frontView: Joi.string().allow('', null).optional(),
    insideView: Joi.string().allow('', null).optional(),
    backView: Joi.string().allow('', null).optional(),
    bootView: Joi.string().allow('', null).optional()
  }).optional()
});

const vehicleBrandSchema = Joi.object({
  brandName: Joi.string().required(),
  logo: Joi.string().allow('', null).optional(),
  country: Joi.string().required(),
  status: Joi.string().valid('active', 'inactive', 'Active', 'Inactive').optional()
});

const vehicleModelSchema = Joi.object({
  brandName: Joi.string().required(), // ObjectId
  category: Joi.string().required(), // ObjectId
  modelName: Joi.string().required(),
  group: Joi.string().required(), // ObjectId
  acAvailable: Joi.boolean().optional(),
  vehicleImages: Joi.array().items(
    Joi.object({
      view: Joi.string().required(),
      url: Joi.string().required()
    })
  ).min(3).required(),
  status: Joi.string().valid('active', 'inactive').optional()
})

// Vehicle Required Document Schema (matches updated model)
const vehicleDocumentSchema = Joi.object({
  docType: Joi.string().valid('insurance', 'tax', 'rc', 'pcu').required(),
  expiryDate: Joi.date().required(),
  fileUrl: Joi.string().required(),
  isVerified: Joi.boolean().optional()
});

const vehicleInstanceSchema = Joi.object({
  registrationNumber: Joi.string().required(),
  vendor: Joi.string().regex(/^[0-9a-fA-F]{24}$/).required().messages({
    'string.pattern.base': 'Vendor ID must be a valid 24-character hex string'
  }),
  zone: Joi.string().regex(/^[0-9a-fA-F]{24}$/).required().messages({
    'string.pattern.base': 'Zone ID must be a valid 24-character hex string'
  }),
  model: Joi.string().regex(/^[0-9a-fA-F]{24}$/).required().messages({
    'string.pattern.base': 'Model ID must be a valid 24-character hex string'
  }),
  category: Joi.string().regex(/^[0-9a-fA-F]{24}$/).required().messages({
    'string.pattern.base': 'Category ID must be a valid 24-character hex string'
  }),
  brand: Joi.string().regex(/^[0-9a-fA-F]{24}$/).required().messages({
    'string.pattern.base': 'Brand ID must be a valid 24-character hex string'
  }),
  group: Joi.string().regex(/^[0-9a-fA-F]{24}$/).required().messages({
    'string.pattern.base': 'Group ID must be a valid 24-character hex string'
  }),
  mileage: Joi.number().required(),
  fuelType: Joi.string().valid('petrol', 'diesel', 'cng', 'electric').default('petrol').optional(),
  description: Joi.string().allow('', null),
  status: Joi.string().valid('active', 'pending', 'inactive', 'on-trip', 'maintenance', 'expired').optional(),
  // Required documents array (optional for creation, can be added later)
  requiredDocuments: Joi.array().items(vehicleDocumentSchema).optional(),
  pcuExpiry: Joi.date().optional(),
  insuranceExpiry: Joi.date().optional(),
  taxExpiry: Joi.date().optional(),
  rcExpiry: Joi.date().optional()
});

// Driver Document Schema (matches updated model)
const driverDocumentSchema = Joi.object({
  docType: Joi.string().valid('drivinglicense', 'idproof', 'policeclearance', 'addressproof', 'bankstatement', 'aadhaar', 'pancard').required(),
  fileUrl: Joi.string().required(),
  isVerified: Joi.boolean().optional()
});

// Driver Account Details Schema
const driverAccountDetailsSchema = Joi.object({
  accountHolderName: Joi.string().required(),
  accountNumber: Joi.string().required(),
  ifscCode: Joi.string().required(),
  bankName: Joi.string().required(),
  branchName: Joi.string().required(),
  upiId: Joi.string().required()
});

// Driver Assignment Details Schema
const driverAssignmentSchema = Joi.object({
  vendorId: Joi.string().regex(/^[0-9a-fA-F]{24}$/).optional().allow(null, '').messages({
    'string.pattern.base': 'Vendor ID must be a valid 24-character hex string'
  }),
  shift: Joi.string().required(),
  vehicleId: Joi.string().regex(/^[0-9a-fA-F]{24}$/).optional().allow(null, '').messages({
    'string.pattern.base': 'Vehicle ID must be a valid 24-character hex string'
  }),
  serviceType: Joi.string().required()
}).unknown(true); // Allow unknown fields like serviceTypes, shiftPreference, etc.

const driverSchema = Joi.object({
  // Basic details
  fullName: Joi.string().min(3).required(),
  email: Joi.string().email().required(),
  phone: Joi.string().min(10).max(15).required(),
  password: Joi.string().min(6).required(),

  // Optional personal details
  dob: Joi.date().optional(),
  registeredAddress: Joi.string().optional().allow(''),
  gender: Joi.string().valid('male', 'female', 'other').optional().allow(''),
  emergencyContact: Joi.object({
    name: Joi.string().optional().allow(''),
    phone: Joi.string().optional().allow('')
  }).optional(),
  experienceYears: Joi.number().min(0).optional(),

  // Professional details
  licenseNumber: Joi.string().optional().allow(''),
  licenseExpiry: Joi.date().optional(),
  backgroundCheck: Joi.object({
    status: Joi.string().valid('pending', 'passed', 'failed', 'not required').optional().allow(''),
    checkDate: Joi.date().optional(),
    agency: Joi.string().optional().allow('')
  }).optional(),

  // Zone is required
  zone: Joi.string().regex(/^[0-9a-fA-F]{24}$/).required().messages({
    'string.pattern.base': 'Zone ID must be a valid 24-character hex string'
  }),

  // Optional references

  driverId: Joi.string().optional(),
  // Documents array (matches updated DocumentSchema)
  documents: Joi.array().items(driverDocumentSchema).optional(),

  // Account details (bank information)
  accountDetails: driverAccountDetailsSchema.required(),

  // Assignment details
  assignmentDetails: driverAssignmentSchema.required(),

  // Status with updated enum values (lowercase as per model)
  status: Joi.string().valid('active', 'inactive', 'ontrip', 'suspended', 'pendingvarification').optional()
});

const vendorDocumentStatusSchema = Joi.object({
  isVerified: Joi.boolean().required()
});

const verifyMobileOtpSchema = Joi.object({
  phone: Joi.string().min(10).max(15).required(),
  otp: Joi.string().length(6).required() // OTP is 6 digits based on sendOtp logic
});

const sendEmailSchema = Joi.object({
  email: Joi.string().email().required(),
  subject: Joi.string().min(3).optional(),
  message: Joi.string().min(5).required()
}).unknown(true); // Allow other fields like attachments if passed in body (though multer handles files)



module.exports = {
  zoneValidation,
  vendorSchema,
  vendorDocumentStatusSchema,
  vehicleCategorySchema,
  vehicleGroupSchema,
  vehicleBrandSchema,
  vehicleModelSchema,
  vehicleInstanceSchema,
  driverSchema,
  verifyMobileOtpSchema,
  sendEmailSchema
};
