import { db } from "@/lib/db";
import { hashPassword } from "@/lib/password";

async function main() {
  // Admin user
  const existing = await db.user.findUnique({ where: { email: "admin@admin.com" } });
  if (!existing) {
    await db.user.create({
      data: {
        email: "admin@admin.com",
        name: "AHE Admin",
        password: hashPassword("admin456"),
        role: "ADMIN",
      },
    });
    console.log("✓ Admin user created: admin@admin.com / admin456");
  } else {
    console.log("• Admin user already exists");
  }

  // Site settings singleton
  await db.siteSetting.upsert({
    where: { id: "singleton" },
    update: {},
    create: { id: "singleton" },
  });
  console.log("✓ Site settings seeded");

  // Services
  const services = [
    {
      slug: "industrial-commercial-ac",
      title: "Industrial & Commercial AC",
      shortDescription: "Heavy-duty cooling solutions for factories, warehouses and large commercial spaces.",
      description:
        "We engineer high-capacity air conditioning systems for industrial and commercial environments. From packaged units to VRV/VRF systems, our solutions deliver reliable, energy-efficient cooling for demanding operations 24/7.",
      icon: "Factory",
      features: ["Packaged & Split Systems", "VRV / VRF Solutions", "Ducted & Cassette Units", "Load Calculation & Design", "Brand-Specific Expertise"],
      order: 1,
    },
    {
      slug: "ac-installation",
      title: "New AC Installation",
      shortDescription: "Complete setup of new air conditioning systems with concealed piping and finishing.",
      description:
        "Turnkey AC installation from equipment selection to final commissioning. Our certified technicians handle complete piping, concealed fitting, electrical work and testing to deliver a flawless, long-lasting installation.",
      icon: "Wrench",
      features: ["Site Survey & Load Calculation", "Concealed Piping & Fitting", "Electrical Connections", "Gas Charging & Testing", "Brand Warranty Support"],
      order: 2,
    },
    {
      slug: "ac-repair-maintenance",
      title: "AC Repair & Maintenance",
      shortDescription: "Fast, reliable repair and general servicing for all AC brands and capacities.",
      description:
        "Comprehensive repair and maintenance services for residential, commercial and industrial air conditioners. We diagnose and fix cooling issues, gas leaks, compressor faults and electrical problems — backed by genuine parts.",
      icon: "Settings",
      features: ["Compressor & PCB Repair", "Gas Refilling & Leak Detection", "Coil & Filter Cleaning", "Electrical Troubleshooting", "Genuine Spare Parts"],
      order: 3,
    },
    {
      slug: "water-chiller",
      title: "Water Chiller Repair & Manufacturing",
      shortDescription: "Expert repair, overhaul and custom manufacturing of water chillers.",
      description:
        "Specialized water chiller services including repair, overhaul, retrofit and custom manufacturing. We work with screw, scroll and centrifugal chillers for industrial process cooling and large HVAC applications.",
      icon: "Snowflake",
      features: ["Chiller Overhaul & Retrofit", "Compressor Replacement", "Refrigerant Conversion", "Custom Chiller Manufacturing", "Performance Optimization"],
      order: 4,
    },
    {
      slug: "air-duct-cleaning",
      title: "Air Duct Cleaning & Fitting",
      shortDescription: "Professional duct cleaning, fabrication and installation for healthier air.",
      description:
        "Improve indoor air quality and HVAC efficiency with professional duct cleaning and fitting services. We fabricate, install and clean GI ducts for commercial kitchens, hospitals, factories and office buildings.",
      icon: "Wind",
      features: ["GI Duct Fabrication", "Deep Duct Cleaning", "Kitchen & Exhaust Ducts", "Hospital & Cleanroom Ducts", "Air Quality Testing"],
      order: 5,
    },
    {
      slug: "commercial-air-dryer",
      title: "Commercial Air Dryer Repair",
      shortDescription: "Repair and manufacturing of refrigerated and desiccant air dryers.",
      description:
        "Keep your compressed air system dry and efficient. We service and manufacture refrigerated and desiccant air dryers for textile, pharmaceutical and industrial applications — ensuring dew point performance.",
      icon: "Droplets",
      features: ["Refrigerated Dryer Service", "Desiccant Dryer Repair", "Heat Exchanger Cleaning", "Dew Point Optimization", "Custom Manufacturing"],
      order: 6,
    },
    {
      slug: "water-cooler",
      title: "Water Cooler Repair",
      shortDescription: "Repair and manufacturing of commercial water coolers and dispensers.",
      description:
        "Expert repair and manufacturing of water coolers for offices, schools, mosques and public spaces. We fix compressors, cooling coils and tanks — and build custom units to your specifications.",
      icon: "GlassWater",
      features: ["Compressor & Coil Repair", "Tank & Tap Replacement", "Stainless Steel Fabrication", "Custom Water Coolers", "Bulk Maintenance Contracts"],
      order: 7,
    },
    {
      slug: "cold-storage",
      title: "Cold Storage Solutions",
      shortDescription: "Design, installation and maintenance of cold rooms and freezer storage.",
      description:
        "Complete cold storage solutions — from cold rooms and blast freezers to walk-in chillers. We design, install and maintain temperature-controlled storage for food, pharmaceuticals and agriculture.",
      icon: "Refrigerator",
      features: ["Cold Room Design & Build", "Blast Freezers", "Insulated Panels", "Temperature Control Systems", "24/7 Monitoring Support"],
      order: 8,
    },
    {
      slug: "amc-contracts",
      title: "AMC Contracts",
      shortDescription: "Annual Maintenance Contracts for worry-free, priority HVAC care.",
      description:
        "Secure peace of mind with our Annual Maintenance Contracts. We offer scheduled servicing, priority response, discounted repairs and detailed reporting — tailored to your equipment and budget.",
      icon: "ShieldCheck",
      features: ["Scheduled Preventive Visits", "Priority Emergency Response", "Discounted Spare Parts", "Detailed Service Reports", "Flexible Contract Tiers"],
      order: 9,
    },
    {
      slug: "ac-sale-purchase",
      title: "AC Sale, Purchase & Exchange",
      shortDescription: "Buy, sell or exchange quality new and second-hand AC units.",
      description:
        "We deal in new and good-condition second-hand air conditioners from leading brands. Buy, sell or exchange your AC with fair valuation, professional inspection and installation support.",
      icon: "Repeat",
      features: ["New AC Sales (All Brands)", "Certified Second-Hand Units", "Fair Exchange Valuation", "Professional Inspection", "Delivery & Installation"],
      order: 10,
    },
  ];

  for (const s of services) {
    await db.service.upsert({
      where: { slug: s.slug },
      update: {},
      create: { ...s, features: JSON.stringify(s.features) },
    });
  }
  console.log(`✓ ${services.length} services seeded`);

  // Industries
  const industries = [
    { slug: "textile", title: "Textile Industry", description: "Process cooling, humidification and chiller systems for spinning, weaving and dyeing units.", icon: "Spool" },
    { slug: "pharmaceutical", title: "Pharmaceutical", description: "Cleanroom HVAC, precise temperature & humidity control and GMP-compliant cooling.", icon: "Pill" },
    { slug: "food-beverage", title: "Food & Beverage", description: "Cold storage, blast freezers and process cooling for food processing and packaging.", icon: "UtensilsCrossed" },
    { slug: "hospitals", title: "Hospitals & Healthcare", description: "Medical-grade air handling, OT ventilation and infection-control ducting.", icon: "HeartPulse" },
    { slug: "commercial", title: "Commercial Buildings", description: "Office towers, malls and hotels — central AC, VRV and ducted solutions.", icon: "Building2" },
    { slug: "data-centers", title: "Data Centers", description: "Precision cooling, redundant chillers and 24/7 critical environment support.", icon: "Server" },
  ];
  for (const ind of industries) {
    await db.industry.upsert({
      where: { slug: ind.slug },
      update: {},
      create: { ...ind },
    });
  }
  console.log(`✓ ${industries.length} industries seeded`);

  // Projects
  const projects = [
    {
      slug: "textile-mill-chiller-plant",
      title: "Textile Mill Chiller Plant Upgrade",
      description: "Replaced aging chiller plant with high-efficiency screw chillers for a major Karachi textile mill.",
      content: "AHE Services engineered and installed a 500 TR screw chiller plant upgrade for a leading textile mill in SITE Area, Karachi. The project included demolition of legacy equipment, installation of two new screw chillers, cooling towers, pumps and a complete BMS-controlled piping network. The upgrade reduced energy consumption by 28% and improved process cooling stability.",
      category: "Industrial",
      location: "SITE Area, Karachi",
      completionDate: "2024-03-15",
      client: "Confidential Textile Mill",
      isFeatured: true,
    },
    {
      slug: "hospital-ot-hvac",
      title: "Hospital Operation Theatre HVAC",
      description: "Designed and installed medical-grade HVAC for operation theatres with HEPA filtration.",
      content: "Complete HVAC design and installation for two operation theatres at a private hospital. The system delivers HEPA-filtered air at controlled temperature and humidity, with laminar flow distribution and pressure cascades meeting international healthcare standards.",
      category: "Healthcare",
      location: "Karachi",
      completionDate: "2024-01-20",
      client: "Private Hospital",
      isFeatured: true,
    },
    {
      slug: "shopping-mall-central-ac",
      title: "Shopping Mall Central AC System",
      description: "Centralized ducted AC system for a 120,000 sq.ft. retail mall.",
      content: "Supplied and installed a centralized chilled-water air conditioning system for a multi-level shopping mall. The project included 4 rooftop packaged units, GI ducting spanning 120,000 sq.ft., 60+ fan coil units and complete BMS integration.",
      category: "Commercial",
      location: "Hyderabad",
      completionDate: "2023-11-10",
      client: "Retail Group",
      isFeatured: true,
    },
    {
      slug: "cold-storage-warehouse",
      title: "Cold Storage Warehouse",
      description: "Turnkey cold room and blast freezer facility for a food distributor.",
      content: "Designed and constructed a 8,000 sq.ft. cold storage warehouse with two cold rooms (2°C) and a blast freezer (-25°C). The facility uses PUF insulated panels, Bitzer compressors and a centralized control system with remote monitoring.",
      category: "Industrial",
      location: "Karachi",
      completionDate: "2023-08-05",
      client: "Food Distributor",
      isFeatured: false,
    },
    {
      slug: "pharma-cleanroom",
      title: "Pharmaceutical Cleanroom HVAC",
      description: "GMP-compliant cleanroom cooling for a pharmaceutical formulation plant.",
      content: "Engineered cleanroom HVAC for a pharmaceutical plant with ISO 8 classification. The system includes desiccant dehumidification, chilled water AHUs, HEPA filtration and precise temperature/humidity control to 21±2°C and 45±5% RH.",
      category: "Healthcare",
      location: "Karachi",
      completionDate: "2023-05-18",
      client: "Pharmaceutical Company",
      isFeatured: true,
    },
    {
      slug: "office-vrv-system",
      title: "Corporate Office VRV System",
      description: "Daikin VRV installation for a 4-floor corporate headquarters.",
      content: "Installed a Daikin VRV IV system across 4 floors of a corporate headquarters, with 35 indoor units, individual zone control and heat recovery. The system delivers 30% energy savings over conventional setups.",
      category: "Commercial",
      location: "Karachi",
      completionDate: "2023-02-28",
      client: "Corporate Client",
      isFeatured: false,
    },
  ];
  for (const p of projects) {
    await db.project.upsert({
      where: { slug: p.slug },
      update: {},
      create: { ...p, images: "[]", videos: "[]" },
    });
  }
  console.log(`✓ ${projects.length} projects seeded`);

  // Testimonials
  const testimonials = [
    { name: "Imran Siddiqui", position: "Plant Manager", company: "Siddiqui Textiles", content: "AHE Services upgraded our entire chiller plant with zero downtime to production. Their engineering team is professional, punctual and genuinely skilled. Highly recommended for industrial HVAC.", rating: 5, order: 1 },
    { name: "Dr. Ayesha Khan", position: "Hospital Administrator", company: "Al-Shifa Hospital", content: "The operation theatre HVAC they installed meets every international standard. Temperature, humidity and air quality are perfectly controlled. Excellent after-sales support too.", rating: 5, order: 2 },
    { name: "Bilal Ahmed", position: "Facilities Head", company: "Mega Mall", content: "Our mall AC runs flawlessly after AHE took over the AMC. Energy bills dropped noticeably and complaints from tenants are almost zero. True professionals.", rating: 5, order: 3 },
    { name: "Farhan Malik", position: "Operations Director", company: "FreshFoods Distribution", content: "They built our cold storage facility from scratch — on time and on budget. The blast freezer performs exactly as promised. A trustworthy engineering partner.", rating: 5, order: 4 },
    { name: "Sana Rauf", position: "Procurement Manager", company: "PharmaLife", content: "For cleanroom HVAC, precision matters. AHE delivered GMP-compliant cooling with flawless humidity control. Their documentation support was excellent for audits.", rating: 5, order: 5 },
    { name: "Kamran Shah", position: "CEO", company: "Shah Enterprises", content: "Bought and exchanged 12 AC units for our offices through AHE. Fair pricing, honest condition grading and clean installation. Will use them again.", rating: 5, order: 6 },
  ];
  for (const t of testimonials) {
    await db.testimonial.create({ data: t });
  }
  console.log(`✓ ${testimonials.length} testimonials seeded`);

  // FAQs
  const faqs = [
    { question: "Which areas do you serve?", answer: "We are based in SITE Area, Karachi and serve clients across Karachi and major cities of Pakistan. For large industrial projects, we mobilize nationwide.", category: "General", order: 1 },
    { question: "Do you provide emergency repair services?", answer: "Yes. We offer 24/7 emergency HVAC repair for industrial and commercial clients under AMC. Call our emergency line 0301-2435144 anytime.", category: "Service", order: 2 },
    { question: "Which AC brands do you service?", answer: "We service all major brands including Panasonic, Hitachi, Mitsubishi, LG, Haier, Daikin, Carrier and more. Our technicians are brand-certified.", category: "Service", order: 3 },
    { question: "What is included in an Annual Maintenance Contract?", answer: "AMC includes scheduled preventive visits, priority emergency response, discounted spare parts, detailed service reports and a dedicated account manager. Tiers are tailored to your equipment.", category: "AMC", order: 4 },
    { question: "Can you manufacture custom chillers or water coolers?", answer: "Yes. We manufacture custom water chillers, air dryers and water coolers to your specifications — including capacity, refrigerant and material requirements.", category: "Manufacturing", order: 5 },
    { question: "Do you offer site surveys and quotations?", answer: "Absolutely. We provide free site surveys, load calculations and detailed quotations for new installations and upgrades. Request a quote through our contact form.", category: "Sales", order: 6 },
    { question: "What payment terms do you offer?", answer: "Payment terms are project-specific. For large installations we offer milestone-based payments. AMC contracts can be billed monthly, quarterly or annually.", category: "Commercial", order: 7 },
    { question: "Are your technicians certified?", answer: "All our technicians are factory-trained and certified. They follow strict safety protocols and carry proper identification and tools.", category: "General", order: 8 },
  ];
  for (const f of faqs) {
    await db.faq.create({ data: f });
  }
  console.log(`✓ ${faqs.length} FAQs seeded`);

  // Blog posts
  const posts = [
    {
      slug: "industrial-chiller-efficiency-guide",
      title: "5 Ways to Improve Industrial Chiller Efficiency",
      excerpt: "Simple, proven strategies to cut energy costs and extend the life of your industrial chiller plant.",
      content: "Industrial chillers can account for a significant share of a facility's energy bill. Here are five proven ways to improve their efficiency:\n\n## 1. Maintain Optimal Condenser Water Temperature\nLower condenser water temperature reduces compressor work. Ensure cooling towers are clean and operating within design parameters.\n\n## 2. Implement Variable Flow Pumping\nVariable primary flow (VPF) pumping reduces pump energy and improves part-load chiller efficiency.\n\n## 3. Clean Tubes and Plates Regularly\nFouling on condenser and evaporator tubes insulates heat transfer surfaces, forcing the compressor to work harder. Schedule cleanings quarterly.\n\n## 4. Use Free Cooling When Possible\nIn cooler months, waterside economizers can bypass chillers entirely, using cooling tower water directly.\n\n## 5. Upgrade to High-Efficiency Compressors\nModern screw and magnetic-bearing centrifugal compressors can cut energy use by 20–30% versus older units.\n\nAt AHE Services, we help industrial clients audit, retrofit and optimize chiller plants for maximum efficiency. Contact us to schedule a facility assessment.",
      category: "Energy Efficiency",
      tags: JSON.stringify(["chillers", "energy efficiency", "industrial"]),
      authorName: "AHE Engineering Team",
      isPublished: true,
      publishedAt: new Date("2024-04-10"),
    },
    {
      slug: "why-annual-maintenance-contracts-matter",
      title: "Why Annual Maintenance Contracts Matter for Commercial HVAC",
      excerpt: "An AMC isn't just a service agreement — it's protection for your investment, uptime and indoor air quality.",
      content: "Commercial HVAC systems are significant capital investments. Here's why an Annual Maintenance Contract (AMC) is essential:\n\n## Predictable Costs\nAMCs convert unpredictable repair bills into a fixed, budgetable expense.\n\n## Priority Response\nWhen your AC fails in peak summer, AMC clients jump the queue. We guarantee response times.\n\n## Extended Equipment Life\nRegular preventive maintenance can extend equipment life by 30–50%, delaying costly replacements.\n\n## Better Indoor Air Quality\nCleaned coils, filters and ducts mean healthier air for occupants and fewer sick days.\n\n## Energy Savings\nA well-maintained system runs efficiently — typically 10–20% lower energy consumption than a neglected one.\n\n## Compliance & Documentation\nFor hospitals, pharma and food industries, AMC records support regulatory audits.\n\nAHE Services offers flexible AMC tiers for every equipment type and budget. Get in touch for a custom proposal.",
      category: "Maintenance",
      tags: JSON.stringify(["AMC", "maintenance", "commercial"]),
      authorName: "AHE Engineering Team",
      isPublished: true,
      publishedAt: new Date("2024-03-22"),
    },
    {
      slug: "air-duct-cleaning-importance",
      title: "The Hidden Cost of Dirty Air Ducts",
      excerpt: "Dirty ducts waste energy, spread contaminants and shorten equipment life. Here's what to look for.",
      content: "Air ducts are the lungs of your building — and when they're dirty, everyone feels it.\n\n## Health Impacts\nDust, mold, bacteria and allergens accumulate in ducts and recirculate indoors. Occupants report headaches, allergies and respiratory issues.\n\n## Energy Waste\nA 0.8mm layer of dust on duct interiors can reduce airflow efficiency by up to 20%. Your fans and compressors work harder to deliver the same cooling.\n\n## Equipment Strain\nRestricted airflow stresses blowers, coils and compressors, accelerating wear and failures.\n\n## When to Clean\n- Visible dust or mold at supply registers\n- Unexplained increase in energy bills\n- After renovations or construction\n- Every 2–3 years for commercial buildings\n\nAHE Services provides professional commercial duct cleaning with inspection cameras and HEPA vacuums. Schedule an assessment today.",
      category: "Air Quality",
      tags: JSON.stringify(["duct cleaning", "air quality", "maintenance"]),
      authorName: "AHE Engineering Team",
      isPublished: true,
      publishedAt: new Date("2024-02-15"),
    },
  ];
  for (const p of posts) {
    await db.blogPost.upsert({
      where: { slug: p.slug },
      update: {},
      create: { ...p, featuredImage: null },
    });
  }
  console.log(`✓ ${posts.length} blog posts seeded`);

  // Team
  const team = [
    { name: "Engr. Hasan Ali", position: "Founder & Chief Engineer", bio: "20+ years in industrial HVAC engineering. Led chiller plant and cold storage projects across Pakistan.", order: 1 },
    { name: "Engr. Bilal Raza", position: "Projects Director", bio: "Specialist in commercial HVAC design and project management. Daikin & Carrier certified.", order: 2 },
    { name: "Imran Sheikh", position: "Service Manager", bio: "Heads our field service team. Expert in chiller overhaul and refrigeration diagnostics.", order: 3 },
    { name: "Adnan Khan", position: "Sales & AMC Lead", bio: "Builds long-term client partnerships through tailored maintenance contracts and honest advice.", order: 4 },
  ];
  for (const m of team) {
    await db.teamMember.create({ data: m });
  }
  console.log(`✓ ${team.length} team members seeded`);

  console.log("\n✅ Seed complete. Admin login: admin@admin.com / admin456");
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await db.$disconnect();
  });
