import { Role, ArticleStatus } from "@prisma/client";
import bcrypt from "bcryptjs";
import { PrismaClient } from "@prisma/client";
import { PrismaPg } from "@prisma/adapter-pg";
import { Pool } from "pg";
import { mockArticles, mockCategories, mockAuthors } from "./data/mockData.ts";

const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter });

async function main() {
  console.log("🌱 Starting database seeding...");

  const salt = await bcrypt.genSalt(10);
  const defaultPasswordHash = await bcrypt.hash("password123", salt);

  // 2. Seed Users (Authors)
  console.log("Seeding users/authors...");
  const authorMap = new Map<string, string>();

  for (const [key, author] of Object.entries(mockAuthors)) {
    let role: Role = Role.REPORTER;
    if (key === "onlinekhabar") {
      role = Role.ADMIN;
    } else if (key === "anil-dhakal") {
      role = Role.EDITOR;
    }

    const user = await prisma.user.upsert({
      where: { username: author.id },
      update: {
        name: author.name,
        avatarUrl: author.avatarUrl,
        role: role,
      },
      create: {
        id: author.id,
        name: author.name,
        username: author.id,
        email: `${author.id}@vutnews.com`,
        passwordHash: defaultPasswordHash,
        role: role,
        avatarUrl: author.avatarUrl,
        bio: author.designation,
      },
    });
    authorMap.set(author.id, user.id);
    console.log(`- Created user: ${user.username} (${user.role})`);
  }

  // 3. Seed Categories
  console.log("Seeding categories...");
  let categoryOrder = 1;
  for (const category of Object.values(mockCategories)) {
    const dbCat = await prisma.category.upsert({
      where: { slug: category.slug },
      update: {
        nameNe: category.nameNe,
        nameEn: category.slug,
      },
      create: {
        id: category.id,
        slug: category.slug,
        nameNe: category.nameNe,
        nameEn: category.slug,
        order: categoryOrder++,
        isActive: true,
      },
    });
    console.log(`- Created category: ${dbCat.nameNe} (${dbCat.slug})`);
  }

  // 4. Seed Articles
  console.log("Seeding articles...");
  for (const article of mockArticles) {
    const fullContent = article.contentNe.join("\n\n");

    const isFeatured = article.slug === "karnali-rural-school-digital-learning";
    const isBreaking = [
      "diesel-petrol-import-decreased",
      "nepal-saf-championship-final",
      "rabi-lamichhane-party-message"
    ].includes(article.slug);

    const isTrending = [
      "kathmandu-vision-2040-balen-shah",
      "nepal-saf-championship-final",
      "nepal-hydro-electricity-export-plan",
      "diesel-petrol-import-decreased"
    ].includes(article.slug);

    const isPremium = [
      "nepal-first-satellite-project",
      "nepal-hydro-electricity-export-plan",
      "organic-tea-ilam-international-market",
      "digital-nepal-framework-citizen-app"
    ].includes(article.slug);

    const viewCount = Math.floor(Math.random() * 850) + 150;
    const shareCount = article.shareCount || Math.floor(Math.random() * 120) + 10;

    const dbArticle = await prisma.article.upsert({
      where: { slug: article.slug },
      update: {
        titleNe: article.titleNe,
        contentNe: fullContent,
        summaryNe: article.summaryNe,
        featuredImage: article.featuredImage,
        captionNe: article.captionNe,
        status: ArticleStatus.PUBLISHED,
        isFeatured,
        isBreaking,
        isTrending,
        isPremium,
      },
      create: {
        id: article.id,
        slug: article.slug,
        titleNe: article.titleNe,
        titleEn: article.titleNe,
        contentNe: fullContent,
        summaryNe: article.summaryNe,
        featuredImage: article.featuredImage,
        captionNe: article.captionNe,
        status: ArticleStatus.PUBLISHED,
        isFeatured,
        isBreaking,
        isTrending,
        isPremium,
        viewCount,
        shareCount,
        publishedAt: new Date(),
        authorId: article.author.id,
        categories: {
          connect: { id: article.category.id },
        },
      },
    });
    console.log(`- Created article: ${dbArticle.slug}`);
  }

  // 5. Seed Advertisements
  console.log("Seeding advertisements...");
  const now = new Date();
  const nextYear = new Date();
  nextYear.setFullYear(now.getFullYear() + 1);

  const mockAdvertisements = [
    {
      title: "मुख्य विज्ञापन (Main Advertisement)",
      position: "POPUP_OVERLAY",
      imageUrl: "/ads/ads-main.png",
      destinationUrl: "https://www.ncell.com.np/",
      startDate: now,
      endDate: nextYear,
      isActive: true,
      order: 0,
    },
    {
      title: "NIC Asia Bank Offer (Navbar)",
      position: "HEADER_LEADERBOARD",
      imageUrl: "/nic.gif",
      destinationUrl: "https://www.nicasiabank.com/",
      startDate: now,
      endDate: nextYear,
      isActive: true,
      order: 0,
    },
    {
      title: "Ncell Giga Pack Offer Leaderboard (Page)",
      position: "HEADER_LEADERBOARD",
      imageUrl: "/ads/alltop.png",
      destinationUrl: "https://www.ncell.com.np/",
      startDate: now,
      endDate: nextYear,
      isActive: true,
      order: 1,
    },
    {
      title: "Ncell Giga Pack Offer",
      position: "HOME_BANNER_MIDDLE",
      imageUrl: "/ads/ads-main.png",
      destinationUrl: "https://www.ncell.com.np/",
      startDate: now,
      endDate: nextYear,
      isActive: true,
      order: 0,
    },
    {
      title: "Nepal Telecom Offer",
      position: "HOME_BOTTOM_BANNER",
      imageUrl: "/ads/ads2.png",
      destinationUrl: "https://www.ntc.net.np/",
      startDate: now,
      endDate: nextYear,
      isActive: true,
      order: 0,
    },
    {
      title: "नेपाल इन्भेष्टमेन्ट बैंक - डोर स्टेप बैंकिङ",
      position: "SIDEBAR_SQUARE_TOP",
      imageUrl: "/ads/ads-3.gif",
      destinationUrl: "https://www.nibl.com.np/",
      startDate: now,
      endDate: nextYear,
      isActive: true,
      order: 0,
    },
    {
      title: "हिमालयन बैंक - साना तथा मझौला उद्यम कर्जा सुविधा",
      position: "SIDEBAR_SQUARE_TOP",
      imageUrl: "/ads/ads-6.gif",
      destinationUrl: "https://www.himalayanbank.com/",
      startDate: now,
      endDate: nextYear,
      isActive: true,
      order: 1,
    },
    {
      title: "मिस नेपाल २०२६ आवेदन खुला",
      position: "SIDEBAR_SQUARE_TOP",
      imageUrl: "/ads/ads-5.gif",
      destinationUrl: "https://www.missnepal.com.np/",
      startDate: now,
      endDate: nextYear,
      isActive: true,
      order: 2,
    },
    {
      title: "नेपाल इन्भेष्टमेन्ट बैंक - डोर स्टेप बैंकिङ (तल्लो)",
      position: "SIDEBAR_SQUARE_BOTTOM",
      imageUrl: "/ads/ads-4.gif",
      destinationUrl: "https://www.nibl.com.np/",
      startDate: now,
      endDate: nextYear,
      isActive: true,
      order: 0,
    },
    {
      title: "महालक्ष्मी विकास बैंक गृह कर्जा",
      position: "SIDEBAR_SQUARE_BOTTOM",
      imageUrl: "/ads/alltop.png",
      destinationUrl: "https://www.mahalaxmibank.com/",
      startDate: now,
      endDate: nextYear,
      isActive: true,
      order: 1,
    },
    {
      title: "In-Article Sponsor 1",
      position: "IN_ARTICLE",
      imageUrl: "/ads/ads-8.gif",
      destinationUrl: "https://www.nibl.com.np/",
      startDate: now,
      endDate: nextYear,
      isActive: true,
      order: 0,
    },
    {
      title: "In-Article Sponsor 2",
      position: "IN_ARTICLE",
      imageUrl: "/ads/ads-9.png",
      destinationUrl: "https://www.mahalaxmibank.com/",
      startDate: now,
      endDate: nextYear,
      isActive: true,
      order: 1,
    },
  ];

  for (const ad of mockAdvertisements) {
    const existing = await prisma.advertisement.findFirst({
      where: { title: ad.title, position: ad.position as any },
    });

    if (existing) {
      await prisma.advertisement.update({
        where: { id: existing.id },
        data: {
          imageUrl: ad.imageUrl,
          destinationUrl: ad.destinationUrl,
          startDate: ad.startDate,
          endDate: ad.endDate,
          isActive: ad.isActive,
          order: ad.order,
        },
      });
      console.log(`- Updated advertisement: ${ad.title} (${ad.position})`);
    } else {
      const created = await prisma.advertisement.create({
        data: {
          title: ad.title,
          position: ad.position as any,
          imageUrl: ad.imageUrl,
          destinationUrl: ad.destinationUrl,
          startDate: ad.startDate,
          endDate: ad.endDate,
          isActive: ad.isActive,
          order: ad.order,
        },
      });
      console.log(`- Created advertisement: ${ad.title} (${ad.position})`);
    }
  }

  // 5. Seed Videos
  console.log("Seeding videos...");
  const mockVideos = [
    {
      title: "४१ अर्ब डलरको विश्वकप अर्थतन्त्र: कसले कति कमायो र गुमायो ?",
      subtitle: "कैयौं देशको वार्षिक जीडीपीभन्दा बढी खर्च हुने फिफा विश्वकपको रहस्यमय आर्थिक पक्ष र देशहरूमा पर्ने दीर्घकालीन असरको विस्तृत विश्लेषण।",
      image: "https://images.unsplash.com/photo-1518063319789-7217e6706b04?w=1000&auto=format&fit=crop&q=80",
      duration: "०८:२४",
      category: "खेलकुद अर्थतन्त्र",
      views: "२.५ लाख पटक हेरिएको",
      youtubeId: "W7P33zP7yEg",
    },
    {
      title: "पहिलो महाधिवेशनको चटारोमा रास्वपा: व्यक्ति केन्द्रित दल बन्ला त संस्थागत?",
      subtitle: "राष्ट्रिय स्वतन्त्र पार्टी (रास्वपा) को पहिलो महाधिवेशन नजिकिँदै गर्दा सांगठनिक ढाँचा र नेतृत्व चयन प्रक्रियाको विश्लेषण।",
      image: "https://images.unsplash.com/photo-1540910419892-4a36d2c3266c?w=500&auto=format&fit=crop&q=80",
      duration: "०५:१५",
      category: "राजनीति",
      views: "९२ हजार पटक हेरिएको",
      youtubeId: "42z1q8-mE9U",
    },
    {
      title: "नेपालमा अमेरिकी लगानीको लहर: म्यारियटको आक्रमक विस्तार र नयाँ सम्भावना",
      subtitle: "पर्यटन र होटल व्यवसायमा बहुराष्ट्रिय चेन ब्रान्ड म्यारियटको प्रवेशसँगै नेपालको आतिथ्यता क्षेत्रमा भित्रिएको विदेशी पुँजी र सम्भावना।",
      image: "https://images.unsplash.com/photo-1566073771259-6a8506099945?w=500&auto=format&fit=crop&q=80",
      duration: "०४:४२",
      category: "आर्थिक बहस",
      views: "६४ हजार पटक हेरिएको",
      youtubeId: "aGgT62fXU_0",
    },
    {
      title: "जग्गा किन्न पाइने तर बेच्न नपाउने हदबन्दी कानुन: घरजग्गा कारोबारीमा तरंग",
      subtitle: "स्थानीय भूमि हदबन्दीसम्बन्धी कानुनी व्यवस्था र रियल इस्टेट व्यवसायीहरूले खेपिरहेका झन्झटहरूको चर्चा।",
      image: "https://images.unsplash.com/photo-1560518883-ce09059eeffa?w=500&auto=format&fit=crop&q=80",
      duration: "०६:१०",
      category: "नीति र कानुन",
      views: "१.१ लाख पटक हेरिएको",
      youtubeId: "4dK_p9q3wJ4",
    },
    {
      title: "बालेन शाहको विकास मोडल: काठमाडौँको बजेटले कसरी ततायो सिंहदरबार?",
      subtitle: "सडक पेटी, पार्क व्यवस्थापन र सार्वजनिक सेवा सुधारका कामहरू मार्फत सिंहदरबार र महानगरपालिकाबीच देखिएको बजेटरी होडबाजी।",
      image: "https://images.unsplash.com/photo-1544735716-392fe2489ffa?w=500&auto=format&fit=crop&q=80",
      duration: "०७:०५",
      category: "सहरी विकास",
      views: "१.८ lakh पटक हेरिएको",
      youtubeId: "vjG0bH8tDts",
    },
  ];

  for (const video of mockVideos) {
    const existing = await prisma.video.findFirst({
      where: { youtubeId: video.youtubeId },
    });

    if (existing) {
      await prisma.video.update({
        where: { id: existing.id },
        data: {
          title: video.title,
          subtitle: video.subtitle,
          image: video.image,
          duration: video.duration,
          category: video.category,
          views: video.views,
        },
      });
      console.log(`- Updated video: ${video.title}`);
    } else {
      await prisma.video.create({
        data: {
          title: video.title,
          subtitle: video.subtitle,
          image: video.image,
          duration: video.duration,
          category: video.category,
          views: video.views,
          youtubeId: video.youtubeId,
        },
      });
      console.log(`- Created video: ${video.title}`);
    }
  }

  // 6. Seed Site Settings
  console.log("Seeding site settings...");
  await prisma.siteSettings.upsert({
    where: { id: "default" },
    update: {
      logoUrl: "/logos/logo.jpg",
      phone: "+977-9822780865",
      email: "info@vutnews.com",
      addressNe: "जोरपाटी-३, काठमाडौं",
      addressEn: "Jorpati-3, Kathmandu",
      publisherNe: "V.U.T Medias Pvt. Ltd.",
      registrationNe: "१५२३५१/०७३/०७४",
      socialLinks: [
        { platform: "Facebook",  url: "https://www.facebook.com/vutnews" },
        { platform: "YouTube",   url: "https://www.youtube.com/@vutnews" },
        { platform: "Twitter",   url: "https://twitter.com/vutnews" },
        { platform: "Instagram", url: "https://www.instagram.com/vutnews" },
      ],
    },
    create: {
      id: "default",
      logoUrl: "/logos/logo.jpg",
      phone: "+977-9822780865",
      email: "info@vutnews.com",
      addressNe: "जोरपाटी-३, काठमाडौं",
      addressEn: "Jorpati-3, Kathmandu",
      publisherNe: "V.U.T Medias Pvt. Ltd.",
      registrationNe: "१५२३५१/०७३/०७४",
      socialLinks: [
        { platform: "Facebook",  url: "https://www.facebook.com/vutnews" },
        { platform: "YouTube",   url: "https://www.youtube.com/@vutnews" },
        { platform: "Twitter",   url: "https://twitter.com/vutnews" },
        { platform: "Instagram", url: "https://www.instagram.com/vutnews" },
      ],
    },
  });
  console.log("- Seeded site settings (registration, phone, email, address, social links)");

  // 7. Seed Jobs
  console.log("Seeding jobs...");
  const mockJobs = [
    {
      title: "वरिष्ठ समाचार सम्पादक (Senior News Editor)",
      titleEn: "Senior News Editor",
      department: "समाचार डेस्क (News Desk)",
      departmentEn: "News Desk",
      location: "काठमाडौं कार्यालय (Kathmandu)",
      type: "पूर्ण-समय (Full-Time)",
      experience: "३-५ वर्ष (3-5 Years)",
      responsibilities: [
        "आर्थिक तथा राजनीतिक समाचारहरूको सम्पादन र भाषा शुद्धीकरण गर्ने।",
        "समाचार डेस्कको दैनिक कार्ययोजना र रिपोर्टरहरूको समन्वय गर्ने।",
        "सत्य, तथ्य र निष्पक्ष समाचार सम्प्रेषणको सुनिश्चितता गर्ने।",
        "महत्वपूर्ण घटनाक्रममा तत्काल सम्पादकीय निर्णय लिने।"
      ],
      qualifications: [
        "पत्रकारिता, आमसञ्चार वा मानविकी संकायमा स्नातक वा स्नातकोत्तर तह उत्तीर्ण।",
        "अनलाइन न्युज पोर्टल वा छापा माध्यममा कम्तीमा ३ वर्ष समाचार सम्पादन गरेको अनुभव।",
        "नेपाली भाषाको व्याकरण, हिज्जे र शैलीमा पूर्ण दख्खल भएको।"
      ],
      description: "समाचार डेस्कको नेतृत्वदायी भूमिका",
      deadline: "२०२६-०७-२०",
      isActive: true,
    },
    {
      title: "बिजनेस रिपोर्टर (Business / Economy Reporter)",
      titleEn: "Business / Economy Reporter",
      department: "रिपोर्टिङ विभाग (Reporting Dept)",
      departmentEn: "Reporting Dept",
      location: "काठमाडौं (स्थलगत र कार्यालय)",
      type: "पूर्ण-समय (Full-Time)",
      experience: "२+ वर्ष (2+ Years)",
      responsibilities: [
        "नेपालको सेयर बजार (NEPSE), बैंकिङ, व्यापार र समग्र अर्थतन्त्रका विषयमा खोजमूलक समाचार तयार गर्ने।",
        "अर्थविद्, उद्यमी र नियामक निकायका प्रमुखहरूसँग अन्तर्वार्ता लिने।",
        "वित्तीय बजारका उतारचढाव र आर्थिक तथ्याङ्कहरूको सरल विश्लेषण प्रस्तुत गर्ने।"
      ],
      qualifications: [
        "अर्थशास्त्र, वाणिज्य शास्त्र वा पत्रकारितामा स्नातक तह उत्तीर्ण।",
        "आर्थिक पत्रकारितामा कम्तीमा २ वर्षको कार्यअनुभव भएको।",
        "नेप्से (NEPSE) र सेयर बजार सम्बन्धी गहिरो बुझाइ भएको।"
      ],
      description: "आर्थिक समाचार संकलन र विश्लेषण",
      deadline: "२०२६-०७-२५",
      isActive: true,
    },
    {
      title: "भिडियो सम्पादक तथा मल्टिमिडिया डिजाइनर (Video Editor)",
      titleEn: "Video Editor & Multimedia Designer",
      department: "मल्टिमिडिया विभाग (Multimedia)",
      departmentEn: "Multimedia",
      location: "काठमाडौं कार्यालय (Studio)",
      type: "पूर्ण-समय वा करार",
      experience: "१-२ वर्ष (1-2 Years)",
      responsibilities: [
        "युट्युब, टिकटक, फेसबुक र इन्स्टाग्रामका लागि समाचारमूलक र विश्लेषणात्मक भिडियोहरू सम्पादन गर्ने।",
        "भिडियो रिपोर्टका लागि आवश्यक आकर्षक ग्राफिक्स, थम्बनेल र एनिमेसन डिजाइन गर्ने।",
        "अडियो क्वालिटी सुधार गर्ने र भिडियोमा पृष्ठभूमि संगीत तथा सबटाइटल संयोजन गर्ने।"
      ],
      qualifications: [
        "Adobe Premiere Pro, After Effects, Photoshop वा समान सफ्टवेयरहरूमा उत्कृष्ट दक्षता।",
        "डिजिटल मिडिया वा समाचार पोर्टलका लागि भिडियो सम्पादन गरेको कम्तीमा १ वर्षको अनुभव।",
        "दृश्य कथा वाचन (Visual Storytelling) मा सिर्जनात्मक सीप भएको।"
      ],
      description: "मल्टिमिडिया र समाचार भिडियो निर्माण",
      deadline: "२०२६-०७-३०",
      isActive: true,
    }
  ];

  for (const job of mockJobs) {
    const existing = await prisma.job.findFirst({
      where: { title: job.title }
    });

    if (!existing) {
      await prisma.job.create({
        data: {
          title: job.title,
          titleEn: job.titleEn,
          department: job.department,
          departmentEn: job.departmentEn,
          location: job.location,
          type: job.type,
          experience: job.experience,
          responsibilities: job.responsibilities,
          qualifications: job.qualifications,
          description: job.description,
          deadline: job.deadline,
          isActive: job.isActive,
        }
      });
      console.log(`- Created job: ${job.title}`);
    } else {
      console.log(`- Job already exists: ${job.title}`);
    }
  }

  console.log("✅ Seeding completed successfully.");
}

main()
  .catch((e) => {
    console.error("❌ Error seeding database:", e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
