import { PrismaClient, UserRole, ServiceArea, DayOfWeek, JobStatus, DocumentType, VerificationStatus, RateType, Gender } from '@prisma/client';
import bcrypt from 'bcryptjs';
import fs from 'fs';
import path from 'path';
import { computeWorkerRankScore } from '../packages/shared/src/workerRank';
import { CITY_DEFINITIONS } from '../packages/shared/src/serviceAreas/data';
import { nationalCustomers, nationalJobs, nationalWorkers } from './seed-national-data';

const prisma = new PrismaClient();

const UPLOAD_DIR = path.resolve(process.env.UPLOAD_DIR || path.join(process.cwd(), 'uploads'));

async function downloadAvatarImage(seed: string): Promise<Buffer | null> {
  const sources = [
    `https://i.pravatar.cc/512?u=${encodeURIComponent(seed)}`,
    `https://api.dicebear.com/7.x/personas/png?seed=${encodeURIComponent(seed)}&size=512`,
  ];

  for (const url of sources) {
    try {
      const response = await fetch(url);
      if (response.ok) {
        return Buffer.from(await response.arrayBuffer());
      }
    } catch {
      // try next source
    }
  }

  return null;
}

async function seedUserAvatar(userId: string, seed: string): Promise<boolean> {
  const buffer = await downloadAvatarImage(seed);
  if (!buffer) return false;

  const avatarsDir = path.join(UPLOAD_DIR, 'avatars');
  fs.mkdirSync(avatarsDir, { recursive: true });

  const filename = `${userId}.jpg`;
  fs.writeFileSync(path.join(avatarsDir, filename), buffer);

  await prisma.user.update({
    where: { id: userId },
    data: { avatarUrl: `/uploads/avatars/${filename}` },
  });

  return true;
}

const categories = [
  { name: 'Carpenter', slug: 'carpenter', icon: '🔨', description: 'Expert carpentry and woodwork services', sortOrder: 1 },
  { name: 'Plumber', slug: 'plumber', icon: '🔧', description: 'Professional plumbing installation and repair', sortOrder: 2 },
  { name: 'Electrician', slug: 'electrician', icon: '⚡', description: 'Licensed electrical services and wiring', sortOrder: 3 },
  { name: 'Painter', slug: 'painter', icon: '🎨', description: 'Interior and exterior painting services', sortOrder: 4 },
  { name: 'Welder', slug: 'welder', icon: '🔥', description: 'Metal fabrication and welding services', sortOrder: 5 },
  { name: 'Mason', slug: 'mason', icon: '🧱', description: 'Masonry and concrete construction', sortOrder: 6 },
  { name: 'Cleaner', slug: 'cleaner', icon: '🧹', description: 'Professional cleaning services', sortOrder: 7 },
  { name: 'Aircon Technician', slug: 'aircon-technician', icon: '❄️', description: 'Air conditioning installation and repair', sortOrder: 8 },
  { name: 'Appliance Repair', slug: 'appliance-repair', icon: '🔌', description: 'Home appliance repair and maintenance', sortOrder: 9 },
  { name: 'Driver', slug: 'driver', icon: '🚗', description: 'Professional driving services', sortOrder: 10 },
  { name: 'Gardener', slug: 'gardener', icon: '🌿', description: 'Landscaping and garden maintenance', sortOrder: 11 },
  { name: 'Handyman', slug: 'handyman', icon: '🛠️', description: 'General home repairs and odd jobs', sortOrder: 12 },
  { name: 'Massage Therapist', slug: 'massage', icon: '💆', description: 'Home-service massage and wellness therapy', sortOrder: 13 },
  { name: 'Errand Runner', slug: 'errand-runner', icon: '🏃', description: 'Grocery runs, pickups, deliveries, and personal errands', sortOrder: 14 },
  { name: 'Mechanic', slug: 'mechanic', icon: '🔩', description: 'Car and motorcycle repair and maintenance', sortOrder: 15 },
  { name: 'Laundry Service', slug: 'laundry', icon: '👕', description: 'Wash, dry, fold, and ironing at home', sortOrder: 16 },
  { name: 'Tailor', slug: 'tailor', icon: '🧵', description: 'Alterations, hemming, and custom sewing', sortOrder: 17 },
  { name: 'Pest Control', slug: 'pest-control', icon: '🐜', description: 'Termite, rodent, and pest treatment', sortOrder: 18 },
  { name: 'Mover', slug: 'mover', icon: '📦', description: 'Furniture moving, hauling, and relocation help', sortOrder: 19 },
  { name: 'Babysitter / Yaya', slug: 'babysitter', icon: '👶', description: 'Childcare, yaya, and nanny services at home', sortOrder: 20 },
  { name: 'Domestic Helper / Katulong', slug: 'domestic-helper', icon: '🧼', description: 'Househelp, kasambahay, and all-around home assistance', sortOrder: 21 },
  { name: 'Private Cook', slug: 'cook', icon: '🍳', description: 'Meal prep, catering, and in-home cooking', sortOrder: 22 },
  { name: 'Barber / Hairdresser', slug: 'barber', icon: '💇', description: 'Haircuts and styling at home or on-site', sortOrder: 23 },
  { name: 'Pet Care', slug: 'pet-care', icon: '🐾', description: 'Dog walking, pet sitting, and grooming help', sortOrder: 24 },
  { name: 'Tutor', slug: 'tutor', icon: '📚', description: 'Private tutoring and homework help', sortOrder: 25 },
  { name: 'Photographer', slug: 'photographer', icon: '📷', description: 'Events, portraits, and product photography', sortOrder: 26 },
  { name: 'Roofer', slug: 'roofer', icon: '🏠', description: 'Roof repair, installation, and waterproofing', sortOrder: 27 },
  { name: 'Tile Setter', slug: 'tile-setter', icon: '🔲', description: 'Floor and wall tile installation and repair', sortOrder: 28 },
  { name: 'Car Washer', slug: 'car-washer', icon: '🚿', description: 'Car wash, detailing, and vehicle cleaning', sortOrder: 29 },
  { name: 'Delivery Rider', slug: 'delivery-rider', icon: '🛵', description: 'Food, parcel, and motorcycle delivery services', sortOrder: 30 },
  { name: 'Caregiver', slug: 'caregiver', icon: '🤝', description: 'Elderly care, patient assistance, and home caregiving', sortOrder: 31 },
  { name: 'Security Guard', slug: 'security-guard', icon: '🛡️', description: 'Residential, building, and event security', sortOrder: 32 },
  { name: 'Locksmith', slug: 'locksmith', icon: '🔑', description: 'Lock installation, key duplication, and lockout help', sortOrder: 33 },
  { name: 'Construction Helper', slug: 'construction-helper', icon: '👷', description: 'Site labor, peon work, and construction assistance', sortOrder: 34 },
  { name: 'Other', slug: 'other', icon: '✨', description: 'Skills and services not listed above', sortOrder: 99 },
];

const serviceAreas: ServiceArea[] = CITY_DEFINITIONS.map((c) => c.key) as ServiceArea[];

const extraCustomers = [
  { email: 'maria@example.com', phone: '+639182222222', firstName: 'Maria', lastName: 'Fernandez' },
  { email: 'ana@example.com', phone: '+639183333333', firstName: 'Ana', lastName: 'Bautista' },
  { email: 'jose@example.com', phone: '+639184444444', firstName: 'Jose', lastName: 'Ramirez' },
];

const customerAccounts = [
  { email: 'customer@example.com', phone: '+639181234567', firstName: 'Juan', lastName: 'Dela Cruz' },
  ...extraCustomers,
  ...nationalCustomers,
];

type SampleCustomerJob = {
  customerEmail: string;
  categorySlug: string;
  title: string;
  description: string;
  location: string;
  latitude: number;
  longitude: number;
  budget: number;
  status?: JobStatus;
  daysUntilNeeded?: number;
};

const sampleCustomerJobs: SampleCustomerJob[] = [
  {
    customerEmail: 'customer@example.com',
    categorySlug: 'carpenter',
    title: 'Kitchen Cabinet Repair',
    description: 'Need carpenter to repair kitchen cabinets. Some doors are loose and need new hinges.',
    location: 'Matina, Davao City',
    latitude: 7.0731,
    longitude: 125.6128,
    budget: 5000,
    daysUntilNeeded: 7,
  },
  {
    customerEmail: 'customer@example.com',
    categorySlug: 'plumber',
    title: 'Bathroom Pipe Leak',
    description: 'Water leaking under the bathroom sink. Need urgent repair.',
    location: 'Buhangin, Davao City',
    latitude: 7.08,
    longitude: 125.62,
    budget: 2500,
    daysUntilNeeded: 2,
  },
  {
    customerEmail: 'customer@example.com',
    categorySlug: 'electrician',
    title: 'Home electrical safety inspection',
    description: 'Licensed electrician needed to inspect panel, outlets, and grounding before renovation.',
    location: 'Lanang, Davao City',
    latitude: 7.085,
    longitude: 125.635,
    budget: 3500,
    daysUntilNeeded: 10,
  },
  {
    customerEmail: 'customer@example.com',
    categorySlug: 'carpenter',
    title: 'Custom built-in closet',
    description: 'Build floor-to-ceiling closet with sliding doors in master bedroom.',
    location: 'Cagayan de Oro',
    latitude: 8.4542,
    longitude: 124.6319,
    budget: 18000,
    daysUntilNeeded: 14,
  },
  {
    customerEmail: 'customer@example.com',
    categorySlug: 'massage',
    title: 'Home-service massage therapy',
    description: 'Two-hour Swedish massage at home after long work week. Prefer licensed therapist.',
    location: 'Downtown, Davao City',
    latitude: 7.065,
    longitude: 125.605,
    budget: 1200,
    daysUntilNeeded: 3,
  },
  {
    customerEmail: 'customer@example.com',
    categorySlug: 'welder',
    title: 'Metal carport frame fabrication',
    description: 'Fabricate and install steel carport frame for two vehicles.',
    location: 'Tacurong',
    latitude: 6.6925,
    longitude: 124.6764,
    budget: 22000,
    daysUntilNeeded: 21,
  },
  {
    customerEmail: 'customer@example.com',
    categorySlug: 'cleaner',
    title: 'Post-renovation deep clean',
    description: 'Full deep clean of 3-bedroom house after minor renovation — dust, windows, floors.',
    location: 'General Santos',
    latitude: 6.1164,
    longitude: 125.1716,
    budget: 4500,
    daysUntilNeeded: 5,
  },
  {
    customerEmail: 'customer@example.com',
    categorySlug: 'mechanic',
    title: 'Motorcycle brake pad replacement',
    description: 'Replace front and rear brake pads on Yamaha NMAX. Parts can be provided.',
    location: 'Zamboanga City',
    latitude: 6.9214,
    longitude: 122.079,
    budget: 1500,
    daysUntilNeeded: 4,
  },
  {
    customerEmail: 'maria@example.com',
    categorySlug: 'electrician',
    title: 'Ceiling fan installation (2 units)',
    description: 'Install two ceiling fans in bedrooms with proper bracing and wiring.',
    location: 'Panabo City',
    latitude: 7.3081,
    longitude: 125.6842,
    budget: 3800,
    daysUntilNeeded: 6,
  },
  {
    customerEmail: 'maria@example.com',
    categorySlug: 'cleaner',
    title: 'Move-in deep cleaning',
    description: 'Deep clean newly rented 2-bedroom apartment before moving in.',
    location: 'Toril, Davao City',
    latitude: 7.018,
    longitude: 125.505,
    budget: 3200,
    daysUntilNeeded: 8,
  },
  {
    customerEmail: 'maria@example.com',
    categorySlug: 'gardener',
    title: 'Backyard landscaping',
    description: 'Trim hedges, replant flower beds, and lay new sod in backyard.',
    location: 'Digos City',
    latitude: 6.7493,
    longitude: 125.3557,
    budget: 8500,
    daysUntilNeeded: 12,
  },
  {
    customerEmail: 'maria@example.com',
    categorySlug: 'mechanic',
    title: 'Car aircon regassing and check',
    description: 'Car AC blowing warm air. Need diagnosis, possible regassing and leak check.',
    location: 'General Santos',
    latitude: 6.12,
    longitude: 125.175,
    budget: 2800,
    daysUntilNeeded: 3,
  },
  {
    customerEmail: 'maria@example.com',
    categorySlug: 'photographer',
    title: 'Birthday party photography',
    description: 'Half-day event coverage for kids birthday party — 50 guests, indoor venue.',
    location: 'Cagayan de Oro',
    latitude: 8.46,
    longitude: 124.64,
    budget: 6000,
    daysUntilNeeded: 18,
  },
  {
    customerEmail: 'maria@example.com',
    categorySlug: 'pet-care',
    title: 'Weekly dog walking service',
    description: 'Walk medium-sized dog 3x per week for one month. Dog is friendly and leash-trained.',
    location: 'Ecoland, Davao City',
    latitude: 7.095,
    longitude: 125.615,
    budget: 4500,
    daysUntilNeeded: 1,
  },
  {
    customerEmail: 'maria@example.com',
    categorySlug: 'handyman',
    title: 'Multiple home fix-it tasks',
    description: 'Fix squeaky door, patch drywall hole, replace door lock, and adjust cabinet hinges.',
    location: 'Nabunturan',
    latitude: 7.6078,
    longitude: 125.9664,
    budget: 4000,
    daysUntilNeeded: 9,
  },
  {
    customerEmail: 'maria@example.com',
    categorySlug: 'laundry',
    title: 'Wash, dry, and fold weekly',
    description: 'Pick up and return laundry service for family of four — sheets and clothes.',
    location: 'Panabo City',
    latitude: 7.31,
    longitude: 125.69,
    budget: 1800,
    daysUntilNeeded: 2,
  },
  {
    customerEmail: 'ana@example.com',
    categorySlug: 'painter',
    title: 'Exterior wall repainting',
    description: 'Repaint front and side exterior walls — prep, primer, and two coats.',
    location: 'Tagum City',
    latitude: 7.4478,
    longitude: 125.8078,
    budget: 15000,
    daysUntilNeeded: 15,
  },
  {
    customerEmail: 'ana@example.com',
    categorySlug: 'aircon-technician',
    title: 'Install new split-type AC',
    description: 'Supply and install 1.5HP split-type aircon in living room with proper drainage.',
    location: 'Matina, Davao City',
    latitude: 7.07,
    longitude: 125.61,
    budget: 28000,
    daysUntilNeeded: 7,
  },
  {
    customerEmail: 'ana@example.com',
    categorySlug: 'roofer',
    title: 'Fix roof leak after typhoon',
    description: 'Locate and repair roof leak in bedroom ceiling. May need partial resealing.',
    location: 'Mati City',
    latitude: 6.9549,
    longitude: 126.2185,
    budget: 9500,
    daysUntilNeeded: 4,
  },
  {
    customerEmail: 'ana@example.com',
    categorySlug: 'tile-setter',
    title: 'Bathroom floor tile installation',
    description: 'Remove old tiles and install new ceramic tiles in 6 sqm bathroom.',
    location: 'Koronadal',
    latitude: 6.5032,
    longitude: 124.8469,
    budget: 12000,
    daysUntilNeeded: 11,
  },
  {
    customerEmail: 'ana@example.com',
    categorySlug: 'tailor',
    title: 'Wedding dress alterations',
    description: 'Take in waist and hem formal gown. Fitting required before event.',
    location: 'Zamboanga City',
    latitude: 6.925,
    longitude: 122.085,
    budget: 3500,
    daysUntilNeeded: 20,
  },
  {
    customerEmail: 'ana@example.com',
    categorySlug: 'pest-control',
    title: 'Termite inspection and treatment',
    description: 'Inspect wooden door frames and treat active termite activity in garage.',
    location: 'Butuan',
    latitude: 8.9475,
    longitude: 125.5406,
    budget: 5500,
    daysUntilNeeded: 6,
  },
  {
    customerEmail: 'ana@example.com',
    categorySlug: 'mover',
    title: 'Apartment move — furniture hauling',
    description: 'Move sofa, bed frame, dining set, and boxes from 2nd floor to new unit.',
    location: 'Bajada, Davao City',
    latitude: 7.078,
    longitude: 125.618,
    budget: 5000,
    daysUntilNeeded: 5,
  },
  {
    customerEmail: 'ana@example.com',
    categorySlug: 'tutor',
    title: 'Grade 10 math tutoring',
    description: 'Twice-weekly algebra and geometry tutoring at home for high school student.',
    location: 'Panabo City',
    latitude: 7.305,
    longitude: 125.68,
    budget: 4000,
    daysUntilNeeded: 3,
    status: 'QUOTED',
  },
  {
    customerEmail: 'jose@example.com',
    categorySlug: 'welder',
    title: 'Repair welded metal gate',
    description: 'Re-weld broken gate hinge and reinforce rusted sections with new steel.',
    location: 'General Santos',
    latitude: 6.115,
    longitude: 125.168,
    budget: 4500,
    daysUntilNeeded: 5,
  },
  {
    customerEmail: 'jose@example.com',
    categorySlug: 'mason',
    title: 'Concrete fence construction',
    description: 'Build 20-meter concrete hollow block fence with steel reinforcement.',
    location: 'Kidapawan',
    latitude: 7.0084,
    longitude: 125.0889,
    budget: 85000,
    daysUntilNeeded: 30,
  },
  {
    customerEmail: 'jose@example.com',
    categorySlug: 'appliance-repair',
    title: 'Refrigerator not cooling',
    description: 'Two-door refrigerator runs but does not cool. Need diagnosis and repair.',
    location: 'Cagayan de Oro',
    latitude: 8.45,
    longitude: 124.625,
    budget: 3200,
    daysUntilNeeded: 2,
  },
  {
    customerEmail: 'jose@example.com',
    categorySlug: 'barber',
    title: 'Home-service family haircuts',
    description: 'Haircuts for 3 family members at home — simple trims and styling.',
    location: 'Calinan, Davao City',
    latitude: 7.19,
    longitude: 125.455,
    budget: 900,
    daysUntilNeeded: 1,
  },
  {
    customerEmail: 'jose@example.com',
    categorySlug: 'cook',
    title: 'Weekly meal prep service',
    description: 'Prepare lunch and dinner for family of five, 3 days per week. Filipino cuisine.',
    location: 'Koronadal',
    latitude: 6.5,
    longitude: 124.85,
    budget: 6000,
    daysUntilNeeded: 4,
  },
  {
    customerEmail: 'jose@example.com',
    categorySlug: 'babysitter',
    title: 'Weekend babysitting',
    description: 'Watch two children (ages 5 and 8) Saturday afternoon while parents attend event.',
    location: 'Samal Island',
    latitude: 7.05,
    longitude: 125.72,
    budget: 1500,
    daysUntilNeeded: 6,
  },
  {
    customerEmail: 'jose@example.com',
    categorySlug: 'errand-runner',
    title: 'Grocery and pharmacy run',
    description: 'Pick up groceries from SM and medicines from pharmacy. List will be provided.',
    location: 'Davao City',
    latitude: 7.073,
    longitude: 125.613,
    budget: 500,
    daysUntilNeeded: 1,
  },
  {
    customerEmail: 'jose@example.com',
    categorySlug: 'electrician',
    title: 'CCTV and outdoor lighting install',
    description: 'Install 4 CCTV cameras and motion-sensor lights with proper wiring.',
    location: 'Cotabato City',
    latitude: 7.2042,
    longitude: 124.2472,
    budget: 15000,
    daysUntilNeeded: 10,
    status: 'QUOTED',
  },
  {
    customerEmail: 'jose@example.com',
    categorySlug: 'driver',
    title: 'Airport pickup and city errands',
    description: 'Full-day driver needed for airport pickup and 3 business stops around city.',
    location: 'Iligan City',
    latitude: 8.228,
    longitude: 124.2452,
    budget: 2500,
    daysUntilNeeded: 8,
  },
  {
    customerEmail: 'ana@example.com',
    categorySlug: 'handyman',
    title: 'Assemble flat-pack furniture',
    description: 'Assemble IKEA wardrobe, bed frame, and desk. Tools available on site.',
    location: 'Valencia City',
    latitude: 7.9064,
    longitude: 125.0942,
    budget: 2800,
    daysUntilNeeded: 4,
  },
  {
    customerEmail: 'customer@example.com',
    categorySlug: 'painter',
    title: 'Interior living room repaint',
    description: 'Repaint living room and hallway — neutral colors, includes minor wall prep.',
    location: 'Surigao City',
    latitude: 9.7853,
    longitude: 125.495,
    budget: 11000,
    daysUntilNeeded: 12,
    status: 'IN_PROGRESS',
  },
];

type SampleReview = {
  customerEmail: string;
  categorySlug: string;
  title: string;
  description: string;
  location: string;
  budget: number;
  qualityRating: number;
  communicationRating: number;
  punctualityRating: number;
  comment: string;
  daysAgo: number;
};

const sampleReviewsByWorker: Record<string, SampleReview[]> = {
  'pedro@worker.com': [
    {
      customerEmail: 'customer@example.com',
      categorySlug: 'carpenter',
      title: 'Built custom bookshelf',
      description: 'Custom wall-mounted bookshelf in living room.',
      location: 'Matina, Davao City',
      budget: 8500,
      qualityRating: 5,
      communicationRating: 5,
      punctualityRating: 4,
      comment: 'Excellent craftsmanship. Pedro finished ahead of schedule and the shelves are perfectly level.',
      daysAgo: 12,
    },
    {
      customerEmail: 'maria@example.com',
      categorySlug: 'carpenter',
      title: 'Door frame repair',
      description: 'Repair swollen wooden door frame after rainy season.',
      location: 'Buhangin, Davao City',
      budget: 3200,
      qualityRating: 5,
      communicationRating: 4,
      punctualityRating: 5,
      comment: 'Very professional and tidy. Would hire again for carpentry work.',
      daysAgo: 28,
    },
    {
      customerEmail: 'ana@example.com',
      categorySlug: 'carpenter',
      title: 'Kitchen cabinet installation',
      description: 'Install pre-fabricated kitchen cabinets and adjust hinges.',
      location: 'Lanang, Davao City',
      budget: 12000,
      qualityRating: 4,
      communicationRating: 5,
      punctualityRating: 4,
      comment: 'Good work overall. Minor adjustment needed on one drawer but Pedro came back the next day.',
      daysAgo: 45,
    },
    {
      customerEmail: 'jose@example.com',
      categorySlug: 'handyman',
      title: 'Fence panel replacement',
      description: 'Replace three damaged fence panels and reinforce posts.',
      location: 'Toril, Davao City',
      budget: 6500,
      qualityRating: 5,
      communicationRating: 5,
      punctualityRating: 5,
      comment: 'Solid work. Fair price and very reliable.',
      daysAgo: 60,
    },
  ],
  'miguel@worker.com': [
    {
      customerEmail: 'customer@example.com',
      categorySlug: 'electrician',
      title: 'Rewired kitchen outlets',
      description: 'Replace old outlets and add GFCI near the sink.',
      location: 'Downtown, Davao City',
      budget: 4500,
      qualityRating: 5,
      communicationRating: 5,
      punctualityRating: 5,
      comment: 'Miguel explained everything clearly and cleaned up after the job. Highly recommended.',
      daysAgo: 8,
    },
    {
      customerEmail: 'maria@example.com',
      categorySlug: 'electrician',
      title: 'Ceiling fan installation',
      description: 'Install two ceiling fans in bedrooms with proper bracing.',
      location: 'Panabo City',
      budget: 3800,
      qualityRating: 4,
      communicationRating: 5,
      punctualityRating: 4,
      comment: 'Fans work great. Arrived a bit late but communicated well.',
      daysAgo: 22,
    },
    {
      customerEmail: 'ana@example.com',
      categorySlug: 'electrician',
      title: 'Circuit breaker troubleshooting',
      description: 'Find and fix tripping breaker affecting aircon line.',
      location: 'Tagum City',
      budget: 2500,
      qualityRating: 5,
      communicationRating: 4,
      punctualityRating: 5,
      comment: 'Found the issue quickly. Professional and knowledgeable.',
      daysAgo: 35,
    },
  ],
  'carlos@worker.com': [
    {
      customerEmail: 'customer@example.com',
      categorySlug: 'plumber',
      title: 'Fixed bathroom pipe leak',
      description: 'Replaced P-trap and sealed leaking joint under sink.',
      location: 'Davao City',
      budget: 1800,
      qualityRating: 5,
      communicationRating: 5,
      punctualityRating: 5,
      comment: 'Carlos came the same day and fixed the leak in under an hour. No mess left behind.',
      daysAgo: 5,
    },
    {
      customerEmail: 'jose@example.com',
      categorySlug: 'plumber',
      title: 'Clogged drain clearing',
      description: 'Clear clogged kitchen drain and inspect pipes.',
      location: 'Digos City',
      budget: 1500,
      qualityRating: 4,
      communicationRating: 4,
      punctualityRating: 4,
      comment: 'Drain is flowing well now. Reasonable rate for emergency service.',
      daysAgo: 18,
    },
    {
      customerEmail: 'maria@example.com',
      categorySlug: 'plumber',
      title: 'Water heater connection',
      description: 'Connect new tankless water heater to existing plumbing.',
      location: 'General Santos',
      budget: 5500,
      qualityRating: 5,
      communicationRating: 5,
      punctualityRating: 4,
      comment: 'Very thorough installation. Tested everything before leaving.',
      daysAgo: 40,
    },
  ],
  'rosa@worker.com': [
    {
      customerEmail: 'ana@example.com',
      categorySlug: 'painter',
      title: 'Interior bedroom repaint',
      description: 'Repaint two bedrooms including prep and trim work.',
      location: 'Davao City',
      budget: 9000,
      qualityRating: 5,
      communicationRating: 5,
      punctualityRating: 5,
      comment: 'Beautiful, even finish. Rosa protected all furniture and floors.',
      daysAgo: 14,
    },
    {
      customerEmail: 'customer@example.com',
      categorySlug: 'painter',
      title: 'Exterior gate repainting',
      description: 'Sand, primer, and paint metal gate and fence section.',
      location: 'Calinan, Davao City',
      budget: 4200,
      qualityRating: 4,
      communicationRating: 5,
      punctualityRating: 4,
      comment: 'Gate looks brand new. Took an extra day due to rain but worth the wait.',
      daysAgo: 30,
    },
  ],
  'marco@worker.com': [
    {
      customerEmail: 'customer@example.com',
      categorySlug: 'handyman',
      title: 'Full bathroom refresh',
      description: 'Retile shower, replace faucet, patch drywall, and repaint walls.',
      location: 'Bajada, Davao City',
      budget: 18500,
      qualityRating: 5,
      communicationRating: 5,
      punctualityRating: 5,
      comment: 'Marco handled plumbing, tiling, and painting in one go. Saved us from hiring three separate workers.',
      daysAgo: 7,
    },
    {
      customerEmail: 'maria@example.com',
      categorySlug: 'electrician',
      title: 'Kitchen lighting upgrade',
      description: 'Install recessed lights and new switches with proper grounding.',
      location: 'General Santos',
      budget: 6200,
      qualityRating: 5,
      communicationRating: 4,
      punctualityRating: 5,
      comment: 'Clean wiring work and he also fixed a loose cabinet hinge while on site.',
      daysAgo: 19,
    },
    {
      customerEmail: 'ana@example.com',
      categorySlug: 'plumber',
      title: 'Laundry room repiping',
      description: 'Replace old galvanized pipes and install new shut-off valves.',
      location: 'Koronadal',
      budget: 7800,
      qualityRating: 4,
      communicationRating: 5,
      punctualityRating: 4,
      comment: 'Reliable across trades. Plumbing was solid and he patched the wall afterward.',
      daysAgo: 33,
    },
    {
      customerEmail: 'jose@example.com',
      categorySlug: 'carpenter',
      title: 'Built-in TV wall unit',
      description: 'Custom MDF entertainment wall with cable management.',
      location: 'Tagum City',
      budget: 14000,
      qualityRating: 5,
      communicationRating: 5,
      punctualityRating: 5,
      comment: 'Excellent carpentry and finished paint job looks store-bought.',
      daysAgo: 52,
    },
  ],
  'antonio@worker.com': [
    {
      customerEmail: 'jose@example.com',
      categorySlug: 'aircon-technician',
      title: 'Split-type AC cleaning',
      description: 'Deep clean two split-type units and check refrigerant levels.',
      location: 'Davao City',
      budget: 2800,
      qualityRating: 5,
      communicationRating: 5,
      punctualityRating: 5,
      comment: 'Both ACs are much colder now. Antonio was on time and very courteous.',
      daysAgo: 10,
    },
    {
      customerEmail: 'maria@example.com',
      categorySlug: 'aircon-technician',
      title: 'AC not cooling diagnosis',
      description: 'Diagnose warm air issue and replace capacitor.',
      location: 'Panabo City',
      budget: 3500,
      qualityRating: 4,
      communicationRating: 4,
      punctualityRating: 5,
      comment: 'Fixed the same day. Explained what went wrong in simple terms.',
      daysAgo: 25,
    },
  ],
};

function daysAgoDate(days: number) {
  const d = new Date();
  d.setDate(d.getDate() - days);
  return d;
}

function daysFromNowDate(days: number) {
  const d = new Date();
  d.setDate(d.getDate() + days);
  return d;
}

const FEMALE_FIRST_NAMES = new Set([
  'Maria',
  'Ana',
  'Rosa',
  'Elena',
  'Sofia',
  'Liza',
  'Grace',
  'Nina',
  'Maya',
  'Isabela',
  'Teresa',
  'Camille',
  'Hannah',
  'Julia',
  'Angie',
  'Carmen',
  'Patricia',
  'Diana',
  'Flora',
  'Clara',
  'Michelle',
  'Bianca',
  'Jasmine',
  'Cynthia',
  'Gina',
  'Marites',
  'Shirley',
  'Amira',
  'Fatima',
  'Christine',
  'Lorna',
  'Angelica',
]);

function inferDemoGender(firstName: string, explicit?: Gender): Gender {
  if (explicit) return explicit;
  return FEMALE_FIRST_NAMES.has(firstName) ? Gender.FEMALE : Gender.MALE;
}

async function ensureCustomerAccounts(passwordHash: string) {
  for (const c of customerAccounts) {
    await prisma.user.upsert({
      where: { email: c.email },
      update: {
        firstName: c.firstName,
        lastName: c.lastName,
        phone: c.phone,
        gender: inferDemoGender(c.firstName),
        emailVerified: true,
        phoneVerified: true,
      },
      create: {
        email: c.email,
        phone: c.phone,
        passwordHash,
        role: UserRole.CUSTOMER,
        firstName: c.firstName,
        lastName: c.lastName,
        gender: inferDemoGender(c.firstName),
        emailVerified: true,
        phoneVerified: true,
      },
    });
  }
}

async function seedSampleCustomerJobs(
  allCategories: { id: string; slug: string }[],
  jobs: SampleCustomerJob[] = sampleCustomerJobs,
) {
  let created = 0;
  let updated = 0;

  for (const sample of jobs) {
    const customer = await prisma.user.findUnique({ where: { email: sample.customerEmail } });
    const category = allCategories.find((c) => c.slug === sample.categorySlug);
    if (!customer || !category) continue;

    const dateNeeded = sample.daysUntilNeeded != null ? daysFromNowDate(sample.daysUntilNeeded) : undefined;
    const status = sample.status ?? JobStatus.OPEN;

    const existing = await prisma.job.findFirst({
      where: {
        title: sample.title,
        customerId: customer.id,
        deletedAt: null,
      },
    });

    if (existing) {
      await prisma.job.update({
        where: { id: existing.id },
        data: {
          categoryId: category.id,
          description: sample.description,
          budget: sample.budget,
          location: sample.location,
          latitude: sample.latitude,
          longitude: sample.longitude,
          dateNeeded,
          status,
          isGuest: false,
          workerId: null,
        },
      });
      updated += 1;
      continue;
    }

    await prisma.job.create({
      data: {
        customerId: customer.id,
        categoryId: category.id,
        title: sample.title,
        description: sample.description,
        budget: sample.budget,
        location: sample.location,
        latitude: sample.latitude,
        longitude: sample.longitude,
        dateNeeded,
        status,
        isGuest: false,
      },
    });
    created += 1;
  }

  console.log(`✅ Seeded ${created} sample customer jobs (${updated} updated, ${jobs.length} total)`);
}

async function seedSampleReviews(passwordHash: string) {
  for (const c of extraCustomers) {
    await prisma.user.upsert({
      where: { email: c.email },
      update: {},
      create: {
        email: c.email,
        phone: c.phone,
        passwordHash,
        role: UserRole.CUSTOMER,
        firstName: c.firstName,
        lastName: c.lastName,
        emailVerified: true,
        phoneVerified: true,
      },
    });
  }

  let created = 0;

  for (const [workerEmail, reviews] of Object.entries(sampleReviewsByWorker)) {
    const workerUser = await prisma.user.findUnique({
      where: { email: workerEmail },
      include: { workerProfile: true },
    });
    if (!workerUser?.workerProfile) continue;

    const workerId = workerUser.workerProfile.id;

    for (const sample of reviews) {
      const existingJob = await prisma.job.findFirst({
        where: { title: sample.title, workerId, deletedAt: null },
      });
      if (existingJob) {
        const hasReview = await prisma.review.findUnique({ where: { jobId: existingJob.id } });
        if (hasReview) continue;
      }

      const customer = await prisma.user.findUnique({ where: { email: sample.customerEmail } });
      const category = await prisma.category.findUnique({ where: { slug: sample.categorySlug } });
      if (!customer || !category) continue;

      const completedAt = daysAgoDate(sample.daysAgo);
      const overallRating =
        (sample.qualityRating + sample.communicationRating + sample.punctualityRating) / 3;

      const job =
        existingJob ??
        (await prisma.job.create({
          data: {
            customerId: customer.id,
            workerId,
            categoryId: category.id,
            title: sample.title,
            description: sample.description,
            budget: sample.budget,
            location: sample.location,
            latitude: 7.0731,
            longitude: 125.6128,
            status: 'COMPLETED',
            createdAt: completedAt,
            updatedAt: completedAt,
          },
        }));

      const existingQuote = await prisma.quotation.findFirst({
        where: { jobId: job.id, workerId },
      });
      if (!existingQuote) {
        await prisma.quotation.create({
          data: {
            jobId: job.id,
            workerId,
            userId: workerUser.id,
            amount: sample.budget,
            status: 'ACCEPTED',
            createdAt: completedAt,
          },
        });
      } else if (existingQuote.status !== 'ACCEPTED') {
        await prisma.quotation.update({
          where: { id: existingQuote.id },
          data: { status: 'ACCEPTED' },
        });
      }

      await prisma.review.create({
        data: {
          jobId: job.id,
          customerId: customer.id,
          workerId,
          qualityRating: sample.qualityRating,
          communicationRating: sample.communicationRating,
          punctualityRating: sample.punctualityRating,
          overallRating,
          comment: sample.comment,
          createdAt: completedAt,
        },
      });

      created += 1;
    }

    const completedJobs = await prisma.job.count({
      where: { workerId, status: 'COMPLETED', deletedAt: null },
    });
    await prisma.workerProfile.update({
      where: { id: workerId },
      data: { totalJobs: completedJobs },
    });
  }

  console.log(`✅ Seeded ${created} sample reviews`);
}

async function syncAllWorkerReviewStats() {
  const workerProfiles = await prisma.workerProfile.findMany({
    where: { deletedAt: null },
    select: { id: true },
  });
  for (const { id } of workerProfiles) {
    const stats = await prisma.review.aggregate({
      where: { workerId: id },
      _avg: { overallRating: true },
      _count: true,
    });
    await prisma.workerProfile.update({
      where: { id },
      data: {
        totalReviews: stats._count,
        averageRating: stats._avg.overallRating ?? 0,
      },
    });
  }
  console.log('✅ Synced worker review stats');
}

async function syncAllWorkerRankScores() {
  const workers = await prisma.workerProfile.findMany({
    where: { deletedAt: null },
    include: { _count: { select: { portfolioImages: true } } },
  });
  for (const worker of workers) {
    const rankScore = computeWorkerRankScore({
      averageRating: worker.averageRating,
      totalReviews: worker.totalReviews,
      isVerified: worker.isVerified,
      portfolioCount: worker._count.portfolioImages,
      experienceYears: worker.experienceYears,
      isAvailable: worker.isAvailable,
      createdAt: worker.createdAt,
    });
    await prisma.workerProfile.update({
      where: { id: worker.id },
      data: { rankScore },
    });
  }
  console.log(`✅ Synced rank scores for ${workers.length} workers`);
}

async function seedLastActiveTimestamps() {
  const users = await prisma.user.findMany({
    where: {
      deletedAt: null,
      role: { in: [UserRole.CUSTOMER, UserRole.WORKER] },
    },
    select: { id: true, email: true },
    orderBy: { createdAt: 'asc' },
  });

  const now = Date.now();
  const offsetsMinutes = [
    1, // Active now
    8,
    25,
    90,
    5 * 60,
    18 * 60,
    2 * 24 * 60,
    5 * 24 * 60,
    12 * 24 * 60,
  ];

  let updated = 0;
  for (let i = 0; i < users.length; i++) {
    const minutesAgo = offsetsMinutes[i % offsetsMinutes.length] + Math.floor(i / offsetsMinutes.length) * 3;
    await prisma.user.update({
      where: { id: users[i].id },
      data: { lastActiveAt: new Date(now - minutesAgo * 60 * 1000) },
    });
    updated += 1;
  }

  // Make a few known demo accounts easy to spot while testing
  const spotlight: Array<{ email: string; minutesAgo: number }> = [
    { email: 'customer@example.com', minutesAgo: 1 },
    { email: 'maria@example.com', minutesAgo: 12 },
    { email: 'pedro@worker.com', minutesAgo: 3 },
    { email: 'marco@worker.com', minutesAgo: 40 },
    { email: 'rosa@worker.com', minutesAgo: 26 * 60 },
  ];

  for (const entry of spotlight) {
    const result = await prisma.user.updateMany({
      where: { email: entry.email },
      data: { lastActiveAt: new Date(now - entry.minutesAgo * 60 * 1000) },
    });
    updated += result.count;
  }

  console.log(`✅ Seeded lastActiveAt for ${users.length} customers/workers`);
}

type SamplePortfolioImage = {
  url: string;
  title: string;
};

const samplePortfoliosByWorker: Record<string, SamplePortfolioImage[]> = {
  'pedro@worker.com': [
    {
      url: 'https://images.unsplash.com/photo-1504148455328-c376907d081c?w=800&auto=format&fit=crop',
      title: 'Custom kitchen cabinets',
    },
    {
      url: 'https://images.unsplash.com/photo-1581539250439-c96614b27be7?w=800&auto=format&fit=crop',
      title: 'Built-in wardrobe',
    },
    {
      url: 'https://images.unsplash.com/photo-1615876230435-c653f631d45d?w=800&auto=format&fit=crop',
      title: 'Hardwood deck repair',
    },
  ],
  'miguel@worker.com': [
    {
      url: 'https://images.unsplash.com/photo-1621905251189-08b45d6a269e?w=800&auto=format&fit=crop',
      title: 'Panel wiring upgrade',
    },
    {
      url: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=800&auto=format&fit=crop',
      title: 'Ceiling fan installation',
    },
    {
      url: 'https://images.unsplash.com/photo-1473341304170-971d9635e766?w=800&auto=format&fit=crop',
      title: 'Outlet and switch replacement',
    },
    {
      url: 'https://images.unsplash.com/photo-1504328345606-18bbc8c9d7d1?w=800&auto=format&fit=crop',
      title: 'Circuit breaker troubleshooting',
    },
  ],
  'carlos@worker.com': [
    {
      url: 'https://images.unsplash.com/photo-1585704032915-c3400f763053?w=800&auto=format&fit=crop',
      title: 'Bathroom pipe leak repair',
    },
    {
      url: 'https://images.unsplash.com/photo-1607472586893-edb57bdc0e39?w=800&auto=format&fit=crop',
      title: 'Kitchen sink installation',
    },
    {
      url: 'https://images.unsplash.com/photo-1581244277943-fe4a9a77709a?w=800&auto=format&fit=crop',
      title: 'Water heater connection',
    },
  ],
  'rosa@worker.com': [
    {
      url: 'https://images.unsplash.com/photo-1562259949-e8e7689d782a?w=800&auto=format&fit=crop',
      title: 'Living room interior repaint',
    },
    {
      url: 'https://images.unsplash.com/photo-1589939705382-10fe03542275?w=800&auto=format&fit=crop',
      title: 'Exterior wall finishing',
    },
    {
      url: 'https://images.unsplash.com/photo-1615874959473-37a9c154a558?w=800&auto=format&fit=crop',
      title: 'Accent wall feature',
    },
    {
      url: 'https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=800&auto=format&fit=crop',
      title: 'Bedroom color refresh',
    },
    {
      url: 'https://images.unsplash.com/photo-1618221195710-dd6b41faaea6?w=800&auto=format&fit=crop',
      title: 'Commercial office touch-up',
    },
  ],
  'marco@worker.com': [
    {
      url: 'https://images.unsplash.com/photo-1581578731548-c64695cc6952?w=800&auto=format&fit=crop',
      title: 'Multi-room home repair',
    },
    {
      url: 'https://images.unsplash.com/photo-1504148455328-c376907d081c?w=800&auto=format&fit=crop',
      title: 'Custom shelving and trim',
    },
    {
      url: 'https://images.unsplash.com/photo-1621905251189-08b45d6a269e?w=800&auto=format&fit=crop',
      title: 'Electrical panel upgrade',
    },
    {
      url: 'https://images.unsplash.com/photo-1562259949-e8e7689d782a?w=800&auto=format&fit=crop',
      title: 'Interior repaint project',
    },
  ],
  'antonio@worker.com': [
    {
      url: 'https://images.unsplash.com/photo-1631545806609-19fe974921e6?w=800&auto=format&fit=crop',
      title: 'Split-type AC installation',
    },
    {
      url: 'https://images.unsplash.com/photo-1581094794329-c8112a89af12?w=800&auto=format&fit=crop',
      title: 'AC unit deep cleaning',
    },
    {
      url: 'https://images.unsplash.com/photo-1621905252507-b35492cc74b4?w=800&auto=format&fit=crop',
      title: 'Refrigerant line repair',
    },
  ],
};

const multiSkillDemoWorker = {
  firstName: 'Marco',
  lastName: 'Villanueva',
  displayName: 'Kuya Marco',
  email: 'marco@worker.com',
  phone: '+639196666666',
  headline: 'Multi-Skilled Handyman — Carpentry, Plumbing, Electrical & Painting',
  bio: 'Versatile home repair specialist with 12 years across the Philippines. One call for carpentry, plumbing, electrical, painting, and general handyman jobs — ideal for renovations and fix-it-all projects.',
  skills: ['handyman', 'carpenter', 'plumber', 'electrician', 'painter'] as const,
  experienceYears: 12,
  hourlyRate: 380,
  serviceAreas: [
    'DAVAO_CITY',
    'GENERAL_SANTOS',
    'KORONADAL',
    'TAGUM_CITY',
  ] satisfies ServiceArea[],
};

type DemoWorkerSeed = {
  firstName: string;
  lastName: string;
  displayName?: string;
  email: string;
  phone: string;
  headline: string;
  bio?: string;
  gender?: Gender;
  skills: string[];
  experienceYears: number;
  hourlyRate: number;
  rateType?: RateType;
  otherSkills?: string;
  isStudent?: boolean;
  serviceAreas: ServiceArea[];
};

const demoWorkers: DemoWorkerSeed[] = [
  {
    firstName: 'Pedro',
    lastName: 'Santos',
    displayName: 'Mang Pedro',
    email: 'pedro@worker.com',
    phone: '+639191111111',
    headline: 'Master Carpenter - 15 Years Experience',
    skills: ['carpenter'],
    experienceYears: 15,
    hourlyRate: 350,
    serviceAreas: ['DAVAO_CITY', 'SAMAL_CITY', 'PANABO_CITY'],
  },
  {
    firstName: 'Miguel',
    lastName: 'Reyes',
    email: 'miguel@worker.com',
    phone: '+639192222222',
    headline: 'Licensed Electrician',
    skills: ['electrician'],
    experienceYears: 10,
    hourlyRate: 400,
    serviceAreas: ['DAVAO_CITY', 'PANABO_CITY', 'TAGUM_CITY'],
  },
  {
    firstName: 'Carlos',
    lastName: 'Garcia',
    email: 'carlos@worker.com',
    phone: '+639193333333',
    headline: 'Expert Plumber',
    skills: ['plumber'],
    experienceYears: 8,
    hourlyRate: 300,
    serviceAreas: ['DAVAO_CITY', 'DIGOS_CITY', 'GENERAL_SANTOS'],
  },
  {
    firstName: 'Rosa',
    lastName: 'Mendoza',
    displayName: 'Ate Rosa',
    email: 'rosa@worker.com',
    phone: '+639194444444',
    headline: 'Professional Painter',
    skills: ['painter'],
    experienceYears: 12,
    hourlyRate: 250,
    serviceAreas: ['DAVAO_CITY', 'SAMAL_CITY', 'SANTO_TOMAS'],
  },
  {
    firstName: 'Antonio',
    lastName: 'Lopez',
    email: 'antonio@worker.com',
    phone: '+639195555555',
    headline: 'Aircon Specialist',
    skills: ['aircon-technician'],
    experienceYears: 7,
    hourlyRate: 450,
    serviceAreas: ['DAVAO_CITY', 'PANABO_CITY', 'TAGUM_CITY'],
  },
  {
    firstName: multiSkillDemoWorker.firstName,
    lastName: multiSkillDemoWorker.lastName,
    email: multiSkillDemoWorker.email,
    phone: multiSkillDemoWorker.phone,
    headline: multiSkillDemoWorker.headline,
    bio: multiSkillDemoWorker.bio,
    skills: [...multiSkillDemoWorker.skills],
    experienceYears: multiSkillDemoWorker.experienceYears,
    hourlyRate: multiSkillDemoWorker.hourlyRate,
    serviceAreas: [...multiSkillDemoWorker.serviceAreas],
  },
  {
    firstName: 'Elena',
    lastName: 'Cruz',
    email: 'elena@worker.com',
    phone: '+639197777777',
    headline: 'Deep Cleaning & Move-Out Specialist',
    skills: ['cleaner'],
    experienceYears: 6,
    hourlyRate: 200,
    serviceAreas: ['DAVAO_CITY', 'SAMAL_CITY', 'PANABO_CITY'],
  },
  {
    firstName: 'Ricardo',
    lastName: 'Torres',
    email: 'ricardo@worker.com',
    phone: '+639198888888',
    headline: 'Structural Welder & Fabricator',
    skills: ['welder', 'handyman'],
    experienceYears: 14,
    hourlyRate: 420,
    serviceAreas: ['GENERAL_SANTOS', 'KORONADAL', 'TACURONG'],
  },
  {
    firstName: 'Benito',
    lastName: 'Aguilar',
    email: 'benito@worker.com',
    phone: '+639199999999',
    headline: 'Masonry & Concrete Expert',
    skills: ['mason', 'tile-setter'],
    experienceYears: 18,
    hourlyRate: 380,
    serviceAreas: ['CAGAYAN_DE_ORO', 'MALAYBALAY', 'VALENCIA_CITY'],
  },
  {
    firstName: 'Sofia',
    lastName: 'Ramirez',
    email: 'sofia@worker.com',
    phone: '+639170000001',
    headline: 'Landscape & Garden Maintenance',
    skills: ['gardener'],
    experienceYears: 9,
    hourlyRate: 220,
    serviceAreas: ['DAVAO_CITY', 'DIGOS_CITY', 'MATI_CITY'],
  },
  {
    firstName: 'James',
    lastName: 'Villareal',
    email: 'james@worker.com',
    phone: '+639170000002',
    headline: 'Auto & Motorcycle Mechanic',
    skills: ['mechanic'],
    experienceYears: 11,
    hourlyRate: 350,
    serviceAreas: ['GENERAL_SANTOS', 'KORONADAL', 'TACURONG'],
  },
  {
    firstName: 'Liza',
    lastName: 'Fernandez',
    email: 'liza@worker.com',
    phone: '+639170000003',
    headline: 'Home Laundry & Ironing Service',
    skills: ['laundry'],
    experienceYears: 5,
    hourlyRate: 180,
    serviceAreas: ['DAVAO_CITY', 'PANABO_CITY', 'TAGUM_CITY'],
  },
  {
    firstName: 'Roberto',
    lastName: 'Tan',
    email: 'roberto@worker.com',
    phone: '+639170000004',
    headline: 'Appliance Repair Technician',
    skills: ['appliance-repair', 'electrician'],
    experienceYears: 10,
    hourlyRate: 320,
    serviceAreas: ['CAGAYAN_DE_ORO', 'ILIGAN_CITY', 'OZAMIZ'],
  },
  {
    firstName: 'Grace',
    lastName: 'Delos Santos',
    email: 'grace@worker.com',
    phone: '+639170000005',
    headline: 'Licensed Massage Therapist — Home Service',
    skills: ['massage'],
    experienceYears: 8,
    hourlyRate: 500,
    serviceAreas: ['DAVAO_CITY', 'TAGUM_CITY', 'DIGOS_CITY'],
  },
  {
    firstName: 'Danny',
    lastName: 'Morales',
    email: 'danny@worker.com',
    phone: '+639170000006',
    headline: 'Personal Driver & Errand Runner',
    skills: ['driver', 'errand-runner'],
    experienceYears: 7,
    hourlyRate: 280,
    serviceAreas: ['DAVAO_CITY', 'PANABO_CITY', 'SAMAL_CITY'],
  },
  {
    firstName: 'Nina',
    lastName: 'Castillo',
    email: 'nina@worker.com',
    phone: '+639170000007',
    headline: 'Tailor & Alterations Specialist',
    skills: ['tailor'],
    experienceYears: 13,
    hourlyRate: 240,
    serviceAreas: ['ZAMBOANGA_CITY', 'PAGADIAN', 'DIPOLOG'],
  },
  {
    firstName: 'Felix',
    lastName: 'Bautista',
    email: 'felix@worker.com',
    phone: '+639170000008',
    headline: 'Pest Control & Termite Treatment',
    skills: ['pest-control'],
    experienceYears: 9,
    hourlyRate: 400,
    serviceAreas: ['BUTUAN', 'SURIGAO_CITY', 'BISLIG'],
  },
  {
    firstName: 'Henry',
    lastName: 'Ocampo',
    email: 'henry@worker.com',
    phone: '+639170000009',
    headline: 'Furniture Mover & Hauling',
    skills: ['mover', 'driver'],
    experienceYears: 6,
    hourlyRate: 300,
    serviceAreas: ['DAVAO_CITY', 'GENERAL_SANTOS', 'DIGOS_CITY'],
  },
  {
    firstName: 'Clara',
    lastName: 'Reyes',
    email: 'clara@worker.com',
    phone: '+639170000010',
    headline: 'Babysitter & Private Tutor',
    skills: ['babysitter', 'tutor'],
    experienceYears: 4,
    hourlyRate: 250,
    serviceAreas: ['DAVAO_CITY', 'PANABO_CITY'],
  },
  {
    firstName: 'Paolo',
    lastName: 'Mendez',
    email: 'paolo@worker.com',
    phone: '+639170000011',
    headline: 'Private Cook & Meal Prep',
    skills: ['cook'],
    experienceYears: 10,
    hourlyRate: 350,
    serviceAreas: ['GENERAL_SANTOS', 'KORONADAL', 'KIDAPAWAN'],
  },
  {
    firstName: 'Vicente',
    lastName: 'Cruz',
    email: 'vicente@worker.com',
    phone: '+639170000012',
    headline: 'Mobile Barber & Hair Stylist',
    skills: ['barber'],
    experienceYears: 8,
    hourlyRate: 280,
    serviceAreas: ['DAVAO_CITY', 'PANABO_CITY', 'SAMAL_CITY'],
  },
  {
    firstName: 'Maya',
    lastName: 'Santos',
    email: 'maya@worker.com',
    phone: '+639170000013',
    headline: 'Pet Sitting & Dog Walking',
    skills: ['pet-care'],
    experienceYears: 3,
    hourlyRate: 200,
    serviceAreas: ['DAVAO_CITY', 'SAMAL_CITY'],
  },
  {
    firstName: 'Lorenzo',
    lastName: 'Iglesias',
    email: 'lorenzo@worker.com',
    phone: '+639170000014',
    headline: 'Event & Portrait Photographer',
    skills: ['photographer'],
    experienceYears: 7,
    hourlyRate: 600,
    serviceAreas: ['CAGAYAN_DE_ORO', 'VALENCIA_CITY', 'MALAYBALAY'],
  },
  {
    firstName: 'Ernesto',
    lastName: 'Padilla',
    email: 'ernesto@worker.com',
    phone: '+639170000015',
    headline: 'Roofing & Tile Installation',
    skills: ['roofer', 'tile-setter', 'mason'],
    experienceYears: 16,
    hourlyRate: 400,
    serviceAreas: ['DAVAO_CITY', 'DIGOS_CITY', 'MATI_CITY', 'MALITA'],
  },
  {
    firstName: 'Jonah',
    lastName: 'Lim',
    email: 'jonah@worker.com',
    phone: '+639170000016',
    headline: 'All-Around Home Repair Handyman',
    skills: ['handyman', 'carpenter', 'plumber'],
    experienceYears: 11,
    hourlyRate: 340,
    serviceAreas: ['ILIGAN_CITY', 'CAGAYAN_DE_ORO', 'OZAMIZ'],
  },
  {
    firstName: 'Isabela',
    lastName: 'Guinto',
    email: 'isabela@worker.com',
    phone: '+639170000017',
    headline: 'Electrician & Aircon Technician',
    skills: ['electrician', 'aircon-technician'],
    experienceYears: 9,
    hourlyRate: 430,
    serviceAreas: ['ZAMBOANGA_CITY', 'DIPOLOG', 'PAGADIAN'],
  },
  {
    firstName: 'Ramon',
    lastName: 'Esteban',
    email: 'ramon@worker.com',
    phone: '+639170000018',
    headline: 'Cleaning & Laundry Services',
    skills: ['cleaner', 'laundry'],
    experienceYears: 5,
    hourlyRate: 190,
    serviceAreas: ['COTABATO_CITY', 'KIDAPAWAN', 'TACURONG'],
  },
  {
    firstName: 'Teresa',
    lastName: 'Navarro',
    email: 'teresa@worker.com',
    phone: '+639170000019',
    headline: 'Home Organizer & Deep Cleaner',
    skills: ['cleaner', 'errand-runner'],
    experienceYears: 4,
    hourlyRate: 210,
    serviceAreas: ['NABUNTURAN', 'TAGUM_CITY', 'PANABO_CITY'],
  },
  {
    firstName: 'Alfredo',
    lastName: 'Dizon',
    email: 'alfredo@worker.com',
    phone: '+639170000020',
    headline: 'Construction Handyman — Build & Repair',
    skills: ['handyman', 'carpenter', 'welder', 'painter'],
    experienceYears: 13,
    hourlyRate: 360,
    serviceAreas: ['GENERAL_SANTOS', 'KORONADAL', 'TACURONG'],
  },
  {
    firstName: 'Camille',
    lastName: 'Ortega',
    email: 'camille@worker.com',
    phone: '+639170000021',
    headline: 'Wellness Massage & Home Care',
    skills: ['massage', 'pet-care', 'babysitter'],
    experienceYears: 6,
    hourlyRate: 320,
    serviceAreas: ['DAVAO_CITY', 'DIGOS_CITY', 'GENERAL_SANTOS'],
  },
  {
    firstName: 'Gilbert',
    lastName: 'Salazar',
    email: 'gilbert@worker.com',
    phone: '+639170000022',
    headline: 'Heavy Equipment Welder & Metal Works',
    skills: ['welder'],
    experienceYears: 20,
    hourlyRate: 480,
    serviceAreas: ['BUTUAN', 'SURIGAO_CITY', 'CAGAYAN_DE_ORO'],
  },
  {
    firstName: 'Hannah',
    lastName: 'Velasco',
    email: 'hannah@worker.com',
    phone: '+639170000023',
    headline: 'Math & Science Private Tutor',
    skills: ['tutor'],
    experienceYears: 5,
    hourlyRate: 300,
    serviceAreas: ['DAVAO_CITY', 'TAGUM_CITY', 'MATI_CITY'],
  },
  {
    firstName: 'Ivan',
    lastName: 'Mercado',
    email: 'ivan@worker.com',
    phone: '+639170000024',
    headline: 'Roof Leak Repair & Waterproofing',
    skills: ['roofer', 'handyman'],
    experienceYears: 12,
    hourlyRate: 370,
    serviceAreas: ['ZAMBOANGA_CITY', 'PAGADIAN', 'COTABATO_CITY'],
  },
  {
    firstName: 'Julia',
    lastName: 'Aquino',
    email: 'julia@worker.com',
    phone: '+639170000025',
    headline: 'Interior Painting & Wall Finishing',
    skills: ['painter', 'tile-setter'],
    experienceYears: 8,
    hourlyRate: 260,
    serviceAreas: ['ILIGAN_CITY', 'MARAWI', 'COTABATO_CITY'],
  },
  {
    firstName: 'Kevin',
    lastName: 'Pascual',
    email: 'kevin@worker.com',
    phone: '+639170000026',
    headline: 'Refrigerator & Washing Machine Repair',
    skills: ['appliance-repair'],
    experienceYears: 7,
    hourlyRate: 310,
    serviceAreas: ['DAVAO_CITY', 'GENERAL_SANTOS', 'BUTUAN'],
  },
  {
    firstName: 'Luis',
    lastName: 'Mendoza',
    email: 'luis@worker.com',
    phone: '+639170000027',
    headline: 'Finish Carpenter & Furniture Builder',
    skills: ['carpenter'],
    experienceYears: 11,
    hourlyRate: 340,
    serviceAreas: ['BISLIG', 'SURIGAO_CITY', 'BUTUAN'],
  },
  {
    firstName: 'Angie',
    lastName: 'Flores',
    email: 'angie@worker.com',
    phone: '+639170000028',
    headline: 'Residential & Office Deep Cleaning',
    skills: ['cleaner'],
    experienceYears: 5,
    hourlyRate: 195,
    serviceAreas: ['BISLIG', 'BUTUAN'],
  },
  {
    firstName: 'Rafael',
    lastName: 'Sotto',
    email: 'rafael@worker.com',
    phone: '+639170000029',
    headline: 'Licensed Electrician — Surigao del Sur',
    skills: ['electrician'],
    experienceYears: 9,
    hourlyRate: 390,
    serviceAreas: ['BISLIG', 'SURIGAO_CITY'],
  },
  {
    firstName: 'Carmen',
    lastName: 'Dela Rosa',
    email: 'carmen@worker.com',
    phone: '+639170000030',
    headline: 'Home-Service Massage & Wellness',
    skills: ['massage'],
    experienceYears: 7,
    hourlyRate: 480,
    serviceAreas: ['BISLIG', 'SURIGAO_CITY'],
  },
  {
    firstName: 'Victor',
    lastName: 'Zamora',
    email: 'victor@worker.com',
    phone: '+639170000031',
    headline: 'Master Plumber — Northern Mindanao',
    skills: ['plumber', 'handyman'],
    experienceYears: 13,
    hourlyRate: 330,
    serviceAreas: ['CAGAYAN_DE_ORO', 'MALAYBALAY', 'VALENCIA_CITY'],
  },
  {
    firstName: 'Patricia',
    lastName: 'Go',
    email: 'patricia@worker.com',
    phone: '+639170000032',
    headline: 'English & Filipino Private Tutor',
    skills: ['tutor'],
    experienceYears: 6,
    hourlyRate: 280,
    serviceAreas: ['SURIGAO_CITY', 'BISLIG', 'BUTUAN'],
  },
  {
    firstName: 'Oscar',
    lastName: 'Navarro',
    email: 'oscar@worker.com',
    phone: '+639170000033',
    headline: 'Motorcycle & Tricycle Mechanic',
    skills: ['mechanic'],
    experienceYears: 10,
    hourlyRate: 320,
    serviceAreas: ['BISLIG', 'BUTUAN', 'SURIGAO_CITY'],
  },
  {
    firstName: 'Diana',
    lastName: 'Castro',
    email: 'diana@worker.com',
    phone: '+639170000034',
    headline: 'Home Cook & Turo-Turo Catering',
    skills: ['cook'],
    experienceYears: 8,
    hourlyRate: 320,
    serviceAreas: ['SURIGAO_CITY', 'BISLIG'],
  },
  {
    firstName: 'Emilio',
    lastName: 'Herrera',
    email: 'emilio@worker.com',
    phone: '+639170000035',
    headline: 'Masonry & Block Laying Specialist',
    skills: ['mason', 'tile-setter'],
    experienceYears: 15,
    hourlyRate: 370,
    serviceAreas: ['OROQUIETA', 'OZAMIZ', 'DIPOLOG'],
  },
  {
    firstName: 'Flora',
    lastName: 'Yap',
    email: 'flora@worker.com',
    phone: '+639170000036',
    headline: 'Custom Sewing & Uniform Tailoring',
    skills: ['tailor'],
    experienceYears: 12,
    hourlyRate: 250,
    serviceAreas: ['CAGAYAN_DE_ORO', 'ILIGAN_CITY'],
  },
  {
    firstName: 'Gabriel',
    lastName: 'Moreno',
    email: 'gabriel@worker.com',
    phone: '+639170000037',
    headline: 'Aircon Install, Clean & Repair',
    skills: ['aircon-technician'],
    experienceYears: 8,
    hourlyRate: 440,
    serviceAreas: ['DIGOS_CITY', 'MATI_CITY', 'MALITA'],
  },
  {
    firstName: 'Helen',
    lastName: 'Castor',
    email: 'helen@worker.com',
    phone: '+639170000038',
    headline: 'Experienced Babysitter & Nanny',
    skills: ['babysitter'],
    experienceYears: 5,
    hourlyRate: 230,
    serviceAreas: ['KIDAPAWAN', 'TACURONG', 'COTABATO_CITY'],
  },
  {
    firstName: 'Roger',
    lastName: 'Dalisay',
    email: 'roger@worker.com',
    phone: '+639170000039',
    headline: 'Roof Repair & Gutter Installation',
    skills: ['roofer', 'handyman'],
    experienceYears: 14,
    hourlyRate: 360,
    serviceAreas: ['MATI_CITY', 'MALITA', 'SANTO_TOMAS'],
  },
  {
    firstName: 'Sheila',
    lastName: 'Borja',
    email: 'sheila@worker.com',
    phone: '+639170000040',
    headline: 'Pest & Termite Control Expert',
    skills: ['pest-control'],
    experienceYears: 10,
    hourlyRate: 410,
    serviceAreas: ['ZAMBOANGA_CITY', 'PAGADIAN', 'DIPOLOG'],
  },
  {
    firstName: 'Tony',
    lastName: 'Agustin',
    email: 'tony@worker.com',
    phone: '+639170000041',
    headline: 'Private Driver & Airport Transfer',
    skills: ['driver', 'errand-runner'],
    experienceYears: 9,
    hourlyRate: 290,
    serviceAreas: ['MARAWI', 'ILIGAN_CITY', 'COTABATO_CITY'],
  },
  {
    firstName: 'Wendy',
    lastName: 'Chua',
    email: 'wendy@worker.com',
    phone: '+639170000042',
    headline: 'Events & Product Photographer',
    skills: ['photographer'],
    experienceYears: 6,
    hourlyRate: 550,
    serviceAreas: ['DAVAO_CITY', 'SAMAL_CITY', 'PANABO_CITY'],
  },
  {
    firstName: 'Xavier',
    lastName: 'Tolentino',
    email: 'xavier@worker.com',
    phone: '+639170000043',
    headline: 'Structural Welder & Gate Fabrication',
    skills: ['welder'],
    experienceYears: 16,
    hourlyRate: 450,
    serviceAreas: ['DIGOS_CITY', 'KIDAPAWAN', 'TACURONG'],
  },
  {
    firstName: 'Yolanda',
    lastName: 'Prieto',
    email: 'yolanda@worker.com',
    phone: '+639170000044',
    headline: 'Laundry Pickup, Wash & Fold',
    skills: ['laundry', 'cleaner'],
    experienceYears: 4,
    hourlyRate: 175,
    serviceAreas: ['GENERAL_SANTOS', 'KORONADAL'],
  },
  {
    firstName: 'Zandro',
    lastName: 'Lim',
    email: 'zandro@worker.com',
    phone: '+639170000045',
    headline: 'Compostela Valley Handyman',
    skills: ['handyman', 'carpenter', 'plumber'],
    experienceYears: 9,
    hourlyRate: 310,
    serviceAreas: ['NABUNTURAN', 'TAGUM_CITY', 'PANABO_CITY'],
  },
  {
    firstName: 'Berto',
    lastName: 'Iglesias',
    email: 'berto@worker.com',
    phone: '+639170000046',
    headline: 'Floor & Wall Tile Specialist',
    skills: ['tile-setter', 'mason'],
    experienceYears: 11,
    hourlyRate: 340,
    serviceAreas: ['DAVAO_CITY', 'DIGOS_CITY', 'GENERAL_SANTOS'],
  },
  {
    firstName: 'Cora',
    lastName: 'Santiago',
    email: 'cora@worker.com',
    phone: '+639170000047',
    headline: 'Pet Sitting & Dog Grooming Help',
    skills: ['pet-care'],
    experienceYears: 4,
    hourlyRate: 210,
    serviceAreas: ['TAGUM_CITY', 'PANABO_CITY', 'NABUNTURAN'],
  },
  {
    firstName: 'Dante',
    lastName: 'Reyes',
    email: 'dante@worker.com',
    phone: '+639170000048',
    headline: 'TV, AC & Appliance Repair',
    skills: ['appliance-repair', 'aircon-technician'],
    experienceYears: 8,
    hourlyRate: 340,
    serviceAreas: ['TACURONG', 'KIDAPAWAN', 'COTABATO_CITY'],
  },
  {
    firstName: 'Elaine',
    lastName: 'Wu',
    email: 'elaine@worker.com',
    phone: '+639170000049',
    headline: 'Mobile Barber & Grooming',
    skills: ['barber'],
    experienceYears: 7,
    hourlyRate: 270,
    serviceAreas: ['CAGAYAN_DE_ORO', 'VALENCIA_CITY', 'MALAYBALAY'],
  },
  {
    firstName: 'Franco',
    lastName: 'Del Mundo',
    email: 'franco@worker.com',
    phone: '+639170000050',
    headline: 'Moving, Hauling & Delivery',
    skills: ['mover', 'driver'],
    experienceYears: 8,
    hourlyRate: 310,
    serviceAreas: ['BUTUAN', 'SURIGAO_CITY', 'BISLIG'],
  },
  {
    firstName: 'Gina',
    lastName: 'Palma',
    email: 'gina@worker.com',
    phone: '+639170000051',
    headline: 'Interior & Exterior House Painter',
    skills: ['painter'],
    experienceYears: 10,
    hourlyRate: 255,
    serviceAreas: ['BISLIG', 'SURIGAO_CITY', 'BUTUAN'],
  },
  {
    firstName: 'Hector',
    lastName: 'Salcedo',
    email: 'hector@worker.com',
    phone: '+639170000052',
    headline: 'Landscape Design & Lawn Care',
    skills: ['gardener', 'handyman'],
    experienceYears: 7,
    hourlyRate: 225,
    serviceAreas: ['SANTO_TOMAS', 'PANABO_CITY', 'TAGUM_CITY'],
  },
  {
    firstName: 'Irene',
    lastName: 'Lacson',
    email: 'irene@worker.com',
    phone: '+639170000053',
    headline: 'Home Wellness & Spa Massage',
    skills: ['massage', 'errand-runner'],
    experienceYears: 6,
    hourlyRate: 460,
    serviceAreas: ['OZAMIZ', 'OROQUIETA', 'DIPOLOG'],
  },
  {
    firstName: 'Jorge',
    lastName: 'Manalo',
    email: 'jorge@worker.com',
    phone: '+639170000054',
    headline: 'Multi-Trade Renovation Specialist',
    skills: ['handyman', 'painter', 'electrician'],
    experienceYears: 14,
    hourlyRate: 370,
    serviceAreas: ['ZAMBOANGA_CITY', 'PAGADIAN'],
  },
  {
    firstName: 'Kristina',
    lastName: 'Abad',
    email: 'kristina@worker.com',
    phone: '+639170000055',
    headline: 'Childcare & Homework Helper',
    skills: ['babysitter', 'tutor'],
    experienceYears: 5,
    hourlyRate: 260,
    serviceAreas: ['GENERAL_SANTOS', 'KORONADAL', 'TACURONG'],
  },
  // --- Workers showcasing registration features (student, other skills, rate types) ---
  {
    firstName: 'Andrea',
    lastName: 'Santos',
    email: 'andrea.student@worker.com',
    phone: '+639170000056',
    headline: 'College Student — Math & Science Tutor',
    bio: 'BS Education student at USEP offering after-school tutoring in math and science. Flexible weekends and evenings around class schedule.',
    skills: ['tutor'],
    experienceYears: 1,
    hourlyRate: 180,
    rateType: RateType.HOURLY,
    isStudent: true,
    serviceAreas: ['DAVAO_CITY', 'PANABO_CITY'],
  },
  {
    firstName: 'Mark',
    lastName: 'Dela Cruz',
    email: 'mark.student@worker.com',
    phone: '+639170000057',
    headline: 'Student Handyman — Part-Time Home Repairs',
    bio: 'Engineering student earning extra income on weekends. Basic carpentry, furniture assembly, and small home fixes.',
    skills: ['handyman'],
    experienceYears: 2,
    hourlyRate: 1200,
    rateType: RateType.DAILY,
    isStudent: true,
    serviceAreas: ['DAVAO_CITY', 'SAMAL_CITY'],
  },
  {
    firstName: 'Jay-ar',
    lastName: 'Villanueva',
    email: 'jayar.other@worker.com',
    phone: '+639170000058',
    headline: 'PC & Phone Repair — Skills Not Listed Above',
    bio: 'Self-taught tech repair specialist. Laptop screen replacement, phone battery swaps, data recovery, and basic network setup.',
    skills: [],
    otherSkills: 'PC & laptop repair, phone screen replacement, data recovery',
    experienceYears: 4,
    hourlyRate: 450,
    rateType: RateType.HOURLY,
    serviceAreas: ['DAVAO_CITY', 'TAGUM_CITY'],
  },
  {
    firstName: 'Lorna',
    lastName: 'Pena',
    email: 'lorna.weekly@worker.com',
    phone: '+639170000059',
    headline: 'Weekly Home Cleaning & Light Errands',
    bio: 'Reliable weekly house cleaning for busy families. Can also run groceries and light errands on cleaning days.',
    skills: ['cleaner', 'errand-runner'],
    otherSkills: 'Weekly pantry organizing & laundry folding',
    experienceYears: 6,
    hourlyRate: 3500,
    rateType: RateType.WEEKLY,
    serviceAreas: ['DAVAO_CITY', 'PANABO_CITY', 'TAGUM_CITY'],
  },
  {
    firstName: 'Rey',
    lastName: 'Castillo',
    email: 'rey.monthly@worker.com',
    phone: '+639170000060',
    headline: 'Electrician — Monthly Maintenance Plans',
    bio: 'Licensed electrician offering monthly maintenance packages for small businesses and rental properties.',
    skills: ['electrician'],
    otherSkills: 'Solar panel wiring & inverter troubleshooting',
    experienceYears: 11,
    hourlyRate: 12000,
    rateType: RateType.MONTHLY,
    serviceAreas: ['GENERAL_SANTOS', 'KORONADAL', 'TACURONG'],
  },
  {
    firstName: 'Paula',
    lastName: 'Ng',
    email: 'paula.student@worker.com',
    phone: '+639170000061',
    headline: 'Student — Event Henna & Face Paint',
    bio: 'Fine arts student available for birthdays, school fairs, and community events. Custom henna designs and kids face painting.',
    skills: [],
    otherSkills: 'Henna art, face painting, event booth setup',
    experienceYears: 1,
    hourlyRate: 250,
    rateType: RateType.HOURLY,
    isStudent: true,
    serviceAreas: ['DAVAO_CITY', 'DIGOS_CITY'],
  },
  {
    firstName: 'Nina',
    lastName: 'Bautista',
    email: 'nina.weekly@worker.com',
    phone: '+639170000062',
    headline: 'Weekly Lawn Care & Garden Maintenance',
    bio: 'Weekly mowing, trimming, and basic garden upkeep for homes and small compounds. Includes weed removal and plant watering.',
    skills: ['gardener'],
    experienceYears: 5,
    hourlyRate: 2800,
    rateType: RateType.WEEKLY,
    serviceAreas: ['DAVAO_CITY', 'SAMAL_CITY', 'PANABO_CITY'],
  },
  {
    firstName: 'Rico',
    lastName: 'Domingo',
    email: 'rico.weekly@worker.com',
    phone: '+639170000063',
    headline: 'Weekly Laundry Pickup & Delivery',
    bio: 'Fixed weekly laundry service — pickup, wash, fold, and return. Ideal for boarding houses and busy professionals.',
    skills: ['laundry', 'cleaner'],
    experienceYears: 4,
    hourlyRate: 2200,
    rateType: RateType.WEEKLY,
    serviceAreas: ['CAGAYAN_DE_ORO', 'ILIGAN_CITY', 'VALENCIA_CITY'],
  },
  {
    firstName: 'Mae',
    lastName: 'Tolosa',
    email: 'mae.weekly@worker.com',
    phone: '+639170000064',
    headline: 'Weekly Babysitter — After-School Care',
    bio: 'Trusted weekly childcare on weekdays after school. Homework help, snacks, and light meal prep until parents get home.',
    skills: ['babysitter', 'tutor'],
    experienceYears: 7,
    hourlyRate: 4000,
    rateType: RateType.WEEKLY,
    serviceAreas: ['GENERAL_SANTOS', 'KORONADAL'],
  },
  {
    firstName: 'Benjie',
    lastName: 'Ocampo',
    email: 'benjie.weekly@worker.com',
    phone: '+639170000065',
    headline: 'Weekly Office Cleaning Contract',
    bio: 'Small office and shop cleaning on a fixed weekly schedule. Floors, restrooms, desks, and trash disposal included.',
    skills: ['cleaner'],
    experienceYears: 8,
    hourlyRate: 4500,
    rateType: RateType.WEEKLY,
    serviceAreas: ['BUTUAN', 'SURIGAO_CITY', 'BISLIG'],
  },
  {
    firstName: 'Carlo',
    lastName: 'Fuentes',
    email: 'carlo.monthly@worker.com',
    phone: '+639170000066',
    headline: 'Monthly Aircon Cleaning & Check-Up',
    bio: 'Monthly aircon maintenance for homes and offices — filter cleaning, coil wash, and basic performance checks.',
    skills: ['aircon-technician'],
    experienceYears: 9,
    hourlyRate: 8500,
    rateType: RateType.MONTHLY,
    serviceAreas: ['DAVAO_CITY', 'TAGUM_CITY', 'PANABO_CITY'],
  },
  {
    firstName: 'Grace',
    lastName: 'Miranda',
    email: 'grace.monthly@worker.com',
    phone: '+639170000067',
    headline: 'Monthly Private Tutor Package',
    bio: 'Four sessions per month for grade school and high school students. Math, English, and science review with progress notes for parents.',
    skills: ['tutor'],
    experienceYears: 6,
    hourlyRate: 6000,
    rateType: RateType.MONTHLY,
    serviceAreas: ['ZAMBOANGA_CITY', 'PAGADIAN', 'DIPOLOG'],
  },
  {
    firstName: 'Nestor',
    lastName: 'Garcia',
    email: 'nestor.monthly@worker.com',
    phone: '+639170000068',
    headline: 'Monthly Driver Retainer — Business Runs',
    bio: 'Dedicated monthly driver for business owners. Bank runs, supplier pickups, and client meetings within the city.',
    skills: ['driver', 'errand-runner'],
    experienceYears: 12,
    hourlyRate: 15000,
    rateType: RateType.MONTHLY,
    serviceAreas: ['CAGAYAN_DE_ORO', 'MALAYBALAY', 'VALENCIA_CITY'],
  },
  {
    firstName: 'Vilma',
    lastName: 'Rosales',
    email: 'vilma.monthly@worker.com',
    phone: '+639170000069',
    headline: 'Monthly Pest Control Service Plan',
    bio: 'Monthly pest inspection and treatment for homes and restaurants. Covers cockroaches, ants, and termite monitoring.',
    skills: ['pest-control'],
    otherSkills: 'Restaurant kitchen fumigation add-on',
    experienceYears: 10,
    hourlyRate: 9500,
    rateType: RateType.MONTHLY,
    serviceAreas: ['DAVAO_CITY', 'GENERAL_SANTOS', 'DIGOS_CITY'],
  },
  ...nationalWorkers,
];

async function seedDemoWorker(
  worker: DemoWorkerSeed,
  passwordHash: string,
  allCategories: { id: string; slug: string }[],
) {
  let categoryIds = worker.skills
    .map((slug) => allCategories.find((c) => c.slug === slug)?.id)
    .filter((id): id is string => Boolean(id));

  if (worker.otherSkills?.trim()) {
    const otherCategory = allCategories.find((c) => c.slug === 'other');
    if (otherCategory && !categoryIds.includes(otherCategory.id)) {
      categoryIds.push(otherCategory.id);
    }
  }

  if (categoryIds.length === 0) {
    throw new Error(`Demo worker ${worker.email} must have at least one skill or otherSkills`);
  }

  const skillLabel =
    worker.skills.length > 0
      ? worker.skills.join(', ')
      : worker.otherSkills?.trim() ?? 'specialist';
  const bio =
    worker.bio ??
    `Professional ${skillLabel} with ${worker.experienceYears} years of experience across the Philippines.`;

  const profileFields = {
    displayName: worker.displayName?.trim() || worker.firstName,
    headline: worker.headline,
    bio,
    experienceYears: worker.experienceYears,
    hourlyRate: worker.hourlyRate,
    rateType: worker.rateType ?? RateType.HOURLY,
    otherSkills: worker.otherSkills?.trim() || null,
    isStudent: worker.isStudent ?? false,
    isVerified: true,
    verificationStatus: VerificationStatus.APPROVED,
    isAvailable: true,
  };

  const user = await prisma.user.upsert({
    where: { email: worker.email },
    update: {
      firstName: worker.firstName,
      lastName: worker.lastName,
      phone: worker.phone,
      gender: inferDemoGender(worker.firstName, worker.gender),
      emailVerified: true,
      phoneVerified: true,
    },
    create: {
      email: worker.email,
      phone: worker.phone,
      passwordHash,
      role: UserRole.WORKER,
      firstName: worker.firstName,
      lastName: worker.lastName,
      gender: inferDemoGender(worker.firstName, worker.gender),
      emailVerified: true,
      phoneVerified: true,
    },
  });

  const profile = await prisma.workerProfile.upsert({
    where: { userId: user.id },
    update: profileFields,
    create: {
      userId: user.id,
      ...profileFields,
    },
  });

  await prisma.workerSkill.deleteMany({ where: { workerId: profile.id } });
  await prisma.workerSkill.createMany({
    data: categoryIds.map((categoryId) => ({ workerId: profile.id, categoryId })),
  });

  await prisma.workerServiceArea.deleteMany({ where: { workerId: profile.id } });
  await prisma.workerServiceArea.createMany({
    data: worker.serviceAreas.map((area) => ({ workerId: profile.id, area })),
  });

  const availabilityDays: DayOfWeek[] = [
    'MONDAY',
    'TUESDAY',
    'WEDNESDAY',
    'THURSDAY',
    'FRIDAY',
    'SATURDAY',
  ];
  const existingAvailability = await prisma.workerAvailability.count({
    where: { workerId: profile.id },
  });
  if (existingAvailability === 0) {
    await prisma.workerAvailability.createMany({
      data: availabilityDays.map((dayOfWeek) => ({
        workerId: profile.id,
        dayOfWeek,
        startTime: '08:00',
        endTime: '17:00',
      })),
    });
  }

  await seedUserAvatar(user.id, worker.email);
}

async function seedAllDemoWorkers(passwordHash: string, allCategories: { id: string; slug: string }[]) {
  let avatarCount = 0;
  for (const worker of demoWorkers) {
    await seedDemoWorker(worker, passwordHash, allCategories);
    const user = await prisma.user.findUnique({ where: { email: worker.email }, select: { avatarUrl: true } });
    if (user?.avatarUrl) avatarCount += 1;
  }
  console.log(`✅ Seeded ${demoWorkers.length} demo workers (Password123! for all)`);
  console.log(`   Includes ${nationalWorkers.length} nationwide Luzon/Visayas/Mindanao workers`);
  console.log(`   Profile photos: ${avatarCount}/${demoWorkers.length}`);
  console.log(
    '   Includes weekly/monthly rate workers (lorna/nina/rico/mae/benjie weekly; rey/carlo/grace/nestor/vilma monthly)'
  );
}

async function seedWorkerPortfolios() {
  let created = 0;

  for (const [email, images] of Object.entries(samplePortfoliosByWorker)) {
    const user = await prisma.user.findUnique({
      where: { email },
      include: { workerProfile: true },
    });
    if (!user?.workerProfile) continue;

    const existing = await prisma.portfolioImage.count({
      where: { workerId: user.workerProfile.id },
    });
    if (existing > 0) continue;

    await prisma.portfolioImage.createMany({
      data: images.map((img, sortOrder) => ({
        workerId: user.workerProfile!.id,
        url: img.url,
        title: img.title,
        sortOrder,
      })),
    });
    created += images.length;
  }

  if (created > 0) {
    console.log(`✅ Seeded ${created} sample portfolio photos`);
  }
}

type VerificationDocSeed = {
  type: DocumentType;
  status: VerificationStatus;
  adminNote?: string;
  daysAgo?: number;
};

type WorkerVerificationSeed = {
  email: string;
  slug: string;
  isVerified: boolean;
  verificationStatus: VerificationStatus;
  documents: VerificationDocSeed[];
};

const demoWorkerVerifications: WorkerVerificationSeed[] = [
  {
    email: 'elena@worker.com',
    slug: 'elena-cruz',
    isVerified: false,
    verificationStatus: 'PENDING',
    documents: [
      { type: 'GOVERNMENT_ID', status: 'PENDING', daysAgo: 2 },
      { type: 'SELFIE', status: 'PENDING', daysAgo: 2 },
    ],
  },
  {
    email: 'ricardo@worker.com',
    slug: 'ricardo-torres',
    isVerified: false,
    verificationStatus: 'PENDING',
    documents: [
      { type: 'GOVERNMENT_ID', status: 'PENDING', daysAgo: 1 },
      { type: 'SELFIE', status: 'PENDING', daysAgo: 1 },
      { type: 'PROOF_OF_ADDRESS', status: 'PENDING', daysAgo: 1 },
    ],
  },
  {
    email: 'benito@worker.com',
    slug: 'benito-aguilar',
    isVerified: false,
    verificationStatus: 'PENDING',
    documents: [{ type: 'GOVERNMENT_ID', status: 'PENDING', daysAgo: 3 }],
  },
  {
    email: 'liza@worker.com',
    slug: 'liza-fernandez',
    isVerified: false,
    verificationStatus: 'PENDING',
    documents: [
      { type: 'GOVERNMENT_ID', status: 'PENDING', daysAgo: 0 },
      { type: 'SELFIE', status: 'PENDING', daysAgo: 0 },
    ],
  },
  {
    email: 'sofia@worker.com',
    slug: 'sofia-ramirez',
    isVerified: false,
    verificationStatus: 'REJECTED',
    documents: [
      {
        type: 'GOVERNMENT_ID',
        status: 'REJECTED',
        daysAgo: 5,
        adminNote: 'ID photo is blurry — please upload a clearer image of your government ID.',
      },
      { type: 'SELFIE', status: 'PENDING', daysAgo: 5 },
    ],
  },
  {
    email: 'james@worker.com',
    slug: 'james-villareal',
    isVerified: false,
    verificationStatus: 'ADDITIONAL_DOCS_REQUIRED',
    documents: [
      { type: 'GOVERNMENT_ID', status: 'APPROVED', daysAgo: 7 },
      {
        type: 'SELFIE',
        status: 'ADDITIONAL_DOCS_REQUIRED',
        daysAgo: 7,
        adminNote: 'Please retake selfie holding your ID next to your face.',
      },
    ],
  },
  {
    email: 'pedro@worker.com',
    slug: 'pedro-santos',
    isVerified: true,
    verificationStatus: 'APPROVED',
    documents: [
      { type: 'GOVERNMENT_ID', status: 'APPROVED', daysAgo: 90 },
      { type: 'SELFIE', status: 'APPROVED', daysAgo: 90 },
    ],
  },
  {
    email: 'marco@worker.com',
    slug: 'marco-villanueva',
    isVerified: true,
    verificationStatus: 'APPROVED',
    documents: [
      { type: 'GOVERNMENT_ID', status: 'APPROVED', daysAgo: 120 },
      { type: 'SELFIE', status: 'APPROVED', daysAgo: 120 },
      { type: 'PROOF_OF_ADDRESS', status: 'APPROVED', daysAgo: 120 },
    ],
  },
  {
    email: 'miguel@worker.com',
    slug: 'miguel-reyes',
    isVerified: true,
    verificationStatus: 'APPROVED',
    documents: [
      { type: 'GOVERNMENT_ID', status: 'APPROVED', daysAgo: 60 },
      { type: 'SELFIE', status: 'APPROVED', daysAgo: 60 },
    ],
  },
];

const verificationDocLabels: Record<DocumentType, string> = {
  GOVERNMENT_ID: 'Government ID',
  SELFIE: 'Selfie with ID',
  PROOF_OF_ADDRESS: 'Proof of Address',
  OTHER: 'Supporting Document',
};

const verificationDocColors: Record<DocumentType, string> = {
  GOVERNMENT_ID: '#1e40af',
  SELFIE: '#047857',
  PROOF_OF_ADDRESS: '#b45309',
  OTHER: '#6b7280',
};

function ensureVerificationPlaceholder(type: DocumentType, workerSlug: string): string {
  const dir = path.join(process.cwd(), 'uploads', 'verifications');
  fs.mkdirSync(dir, { recursive: true });
  const filename = `demo-${workerSlug}-${type.toLowerCase()}.svg`;
  const filepath = path.join(dir, filename);
  const label = verificationDocLabels[type];
  const color = verificationDocColors[type];

  const svg = `<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="640" height="480" viewBox="0 0 640 480">
  <rect width="640" height="480" fill="#f1f5f9"/>
  <rect x="32" y="32" width="576" height="416" rx="16" fill="#ffffff" stroke="#cbd5e1" stroke-width="2"/>
  <rect x="32" y="32" width="576" height="72" rx="16" fill="${color}"/>
  <text x="64" y="78" fill="#ffffff" font-family="Arial, sans-serif" font-size="28" font-weight="700">${label}</text>
  <text x="64" y="160" fill="#0f172a" font-family="Arial, sans-serif" font-size="22" font-weight="600">Demo verification document</text>
  <text x="64" y="200" fill="#64748b" font-family="Arial, sans-serif" font-size="18">${workerSlug.replace(/-/g, ' ')}</text>
  <text x="64" y="240" fill="#64748b" font-family="Arial, sans-serif" font-size="16">eHandyHire seed data — not a real ID</text>
  <rect x="64" y="280" width="512" height="120" rx="8" fill="#f8fafc" stroke="#e2e8f0"/>
  <text x="88" y="320" fill="#94a3b8" font-family="Arial, sans-serif" font-size="14">Document type: ${type.replace(/_/g, ' ')}</text>
  <text x="88" y="348" fill="#94a3b8" font-family="Arial, sans-serif" font-size="14">For admin verification demo only</text>
</svg>`;

  fs.writeFileSync(filepath, svg);
  return `/uploads/verifications/${filename}`;
}

async function seedWorkerVerificationDocuments() {
  let created = 0;
  let pending = 0;

  for (const entry of demoWorkerVerifications) {
    const user = await prisma.user.findUnique({
      where: { email: entry.email },
      include: { workerProfile: true },
    });
    if (!user?.workerProfile) continue;

    const workerId = user.workerProfile.id;

    await prisma.verificationDocument.deleteMany({ where: { workerId } });

    for (const doc of entry.documents) {
      const submittedAt = daysAgoDate(doc.daysAgo ?? 0);
      const reviewed =
        doc.status !== 'PENDING'
          ? daysAgoDate(Math.max(0, (doc.daysAgo ?? 0) - 1))
          : null;

      await prisma.verificationDocument.create({
        data: {
          workerId,
          type: doc.type,
          url: ensureVerificationPlaceholder(doc.type, `${entry.slug}-${doc.type.toLowerCase()}`),
          status: doc.status,
          adminNote: doc.adminNote ?? null,
          reviewedAt: reviewed,
          createdAt: submittedAt,
          updatedAt: reviewed ?? submittedAt,
        },
      });
      created += 1;
      if (doc.status === 'PENDING') pending += 1;
    }

    await prisma.workerProfile.update({
      where: { id: workerId },
      data: {
        isVerified: entry.isVerified,
        verificationStatus: entry.verificationStatus,
      },
    });
  }

  console.log(
    `✅ Seeded ${created} demo verification documents (${pending} pending review) for ${demoWorkerVerifications.length} workers`
  );
}

async function main() {
  console.log('🌱 Seeding eHandyHire database...');

  // Seed categories
  for (const cat of categories) {
    await prisma.category.upsert({
      where: { slug: cat.slug },
      update: cat,
      create: cat,
    });
  }
  console.log(`✅ Seeded ${categories.length} categories`);

  const passwordHash = await bcrypt.hash('Password123!', 12);

  // Seed admin user
  const admin = await prisma.user.upsert({
    where: { email: 'admin@ehandyhire.com' },
    update: {},
    create: {
      email: 'admin@ehandyhire.com',
      phone: '+639171234567',
      passwordHash,
      role: UserRole.ADMIN,
      firstName: 'Admin',
      lastName: 'User',
      emailVerified: true,
      phoneVerified: true,
    },
  });
  console.log('✅ Seeded admin user (admin@ehandyhire.com / Password123!)');

  // Seed sample customer
  const customer = await prisma.user.upsert({
    where: { email: 'customer@example.com' },
    update: {},
    create: {
      email: 'customer@example.com',
      phone: '+639181234567',
      passwordHash,
      role: UserRole.CUSTOMER,
      firstName: 'Juan',
      lastName: 'Dela Cruz',
      emailVerified: true,
      phoneVerified: true,
      customerProfile: {
        create: {
          address: '123 Rizal Street',
          city: 'Davao City',
          latitude: 7.0731,
          longitude: 125.6128,
          bio: 'Looking for reliable workers in Davao',
        },
      },
    },
  });
  console.log('✅ Seeded sample customer (customer@example.com / Password123!)');

  const allCategories = await prisma.category.findMany();

  await seedAllDemoWorkers(passwordHash, allCategories);

  await ensureCustomerAccounts(passwordHash);
  await seedSampleCustomerJobs(allCategories, [...sampleCustomerJobs, ...nationalJobs]);

  await seedSampleReviews(passwordHash);
  await seedWorkerPortfolios();
  await seedWorkerVerificationDocuments();
  await syncAllWorkerReviewStats();
  await syncAllWorkerRankScores();
  await seedLastActiveTimestamps();

  console.log('🎉 Seeding complete!');
}

main()
  .catch((e) => {
    console.error('❌ Seed failed:', e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
