const { sequelize, User, Book, Voucher, Review, Purchase, PurchaseItem, Order, OrderItem } = require('../models');
const bcrypt = require('bcryptjs');

const seedDatabase = async () => {
    try {
        await sequelize.sync({ force: true });
        console.log('Database synced!');

        // 1. Seed Users
        const hashedPassword = await bcrypt.hash('password123', 10);
        const users = await User.bulkCreate([
            {
                username: 'admin',
                name: 'Admin User',
                email: 'admin@tokobuku.com',
                password: hashedPassword,
                role: 'admin',
                phone: '081234567890',
                address: 'Admin HQ, Jakarta',
                image: 'https://randomuser.me/api/portraits/men/1.jpg',
                status: 'Active'
            },
            {
                username: 'johndoe',
                name: 'John Doe',
                email: 'john@example.com',
                password: hashedPassword,
                role: 'user',
                phone: '081234567891',
                address: 'Jl. Jendral Sudirman No. 1, Jakarta Selatan',
                image: 'https://randomuser.me/api/portraits/men/2.jpg',
                status: 'Active'
            },
            {
                username: 'janedoe',
                name: 'Jane Doe',
                email: 'jane@example.com',
                password: hashedPassword,
                role: 'user',
                phone: '081234567892',
                address: 'Jl. Ahmad Yani No. 2, Bandung',
                image: 'https://randomuser.me/api/portraits/women/1.jpg',
                status: 'Active'
            },
            {
                username: 'budi',
                name: 'Budi Santoso',
                email: 'budi@example.com',
                password: hashedPassword,
                role: 'user',
                phone: '081234567893',
                address: 'Jl. Malioboro No. 5, Yogyakarta',
                image: 'https://randomuser.me/api/portraits/men/3.jpg',
                status: 'Active'
            },
            {
                username: 'siti',
                name: 'Siti Aminah',
                email: 'siti@example.com',
                password: hashedPassword,
                role: 'user',
                phone: '081234567894',
                address: 'Jl. Pahlawan No. 10, Surabaya',
                image: 'https://randomuser.me/api/portraits/women/2.jpg',
                status: 'Inactive'
            }
        ]);
        console.log('Users seeded!');

        // 2. Seed Books (15 Items)
        const booksData = [
            {
                title: "Laskar Pelangi",
                author: "Andrea Hirata",
                publisher: "Bentang Pustaka",
                publish_date: "2005-09-01",
                isbn: "978-979-1227-91-8",
                price: 89000,
                originalPrice: 125000,
                stock: 50,
                rating: 4.8,
                image: "https://cdn.gramedia.com/uploads/items/9789791227918_laskar-pelangi-hard-cover__w149_hauto.jpg",
                category: "Novel",
                description: "Novel inspiratif tentang pendidikan di Belitong.",
                tags: ["Best Seller", "Inspirasi", "Pendidikan"],
                discount: 28
            },
            {
                title: "Dilan 1990",
                author: "Pidi Baiq",
                publisher: "Pastel Books",
                publish_date: "2014-04-01",
                isbn: "978-602-7870-41-3",
                price: 75000,
                originalPrice: 95000,
                stock: 45,
                rating: 4.7,
                image: "https://upload.wikimedia.org/wikipedia/id/f/f3/Dilan_Bagian_Pertama_Sampul.jpg",
                category: "Romance",
                description: "Kisah cinta remaja di Bandung tahun 1990.",
                tags: ["Romance", "Remaja", "Best Seller"],
                discount: 21
            },
            {
                title: "Bumi Manusia",
                author: "Pramoedya Ananta Toer",
                publisher: "Lentera Dipantara",
                publish_date: "1980-08-25",
                isbn: "978-979-97312-3-8",
                price: 135000,
                originalPrice: 150000,
                stock: 30,
                rating: 4.9,
                image: "https://cdn.gramedia.com/uploads/items/9789799731238_Bumi-Manusia-Cover-Baru-2015__w149_hauto.jpg",
                category: "Sejarah",
                description: "Roman sejarah pergerakan nasional di awal abad 20.",
                tags: ["Sejarah", "Sastra", "Klasik"],
                discount: 10
            },
            {
                title: "Harry Potter dan Batu Bertuah",
                author: "J.K. Rowling",
                publisher: "Gramedia Pustaka Utama",
                publish_date: "2000-09-01",
                isbn: "978-602-03-3765-3",
                price: 120000,
                originalPrice: 150000,
                stock: 60,
                rating: 4.9,
                image: "https://cdn.gramedia.com/uploads/items/9786020337653_Harry-Potter-Dan-Batu-Bertuah-Cover-Baru-2017__w149_hauto.jpg",
                category: "Fantasi",
                description: "Petualangan Harry Potter di tahun pertama Hogwarts.",
                tags: ["Fantasi", "Sihir", "Petualangan"],
                discount: 20
            },
            {
                title: "Filosofi Teras",
                author: "Henry Manampiring",
                publisher: "Kompas",
                publish_date: "2018-11-26",
                isbn: "978-602-412-518-9",
                price: 98000,
                originalPrice: 110000,
                stock: 40,
                rating: 4.8,
                image: "https://cdn.gramedia.com/uploads/items/9786024125189_Filosofi-Teras-New__w149_hauto.jpg",
                category: "Pengembangan Diri",
                description: "Penerapan filsafat Stoa dalam kehidupan sehari-hari.",
                tags: ["Self Help", "Filsafat", "Best Seller"],
                discount: 10
            },
            {
                title: "Atomic Habits",
                author: "James Clear",
                publisher: "Gramedia Pustaka Utama",
                publish_date: "2019-09-16",
                isbn: "978-602-06-3317-6",
                price: 108000,
                originalPrice: 120000,
                stock: 55,
                rating: 4.9,
                image: "https://cdn.gramedia.com/uploads/items/9786020633176_Atomic-Habits-Perubahan-Kecil-yang-Memberikan-Hasil-Luar-Biasa__w149_hauto.jpg",
                category: "Pengembangan Diri",
                description: "Cara mudah dan terbukti untuk membentuk kebiasaan baik.",
                tags: ["Productivity", "Self Help", "International Best Seller"],
                discount: 10
            },
            {
                title: "Laut Bercerita",
                author: "Leila S. Chudori",
                publisher: "KPG (Kepustakaan Populer Gramedia)",
                publish_date: "2017-10-01",
                isbn: "978-602-424-694-5",
                price: 115000,
                originalPrice: 125000,
                stock: 25,
                rating: 4.8,
                image: "https://cdn.gramedia.com/uploads/items/9786024246945_Laut-Bercerita__w149_hauto.jpg",
                category: "Fiksi",
                description: "Novel tentang aktivis mahasiswa tahun 1998.",
                tags: ["Sejarah", "Fiksi", "Drama"],
                discount: 8
            },
            {
                title: "Cantik Itu Luka",
                author: "Eka Kurniawan",
                publisher: "Gramedia Pustaka Utama",
                publish_date: "2002-01-01",
                isbn: "978-602-03-1258-2",
                price: 145000,
                originalPrice: 160000,
                stock: 20,
                rating: 4.7,
                image: "https://cdn.gramedia.com/uploads/items/9786020312582_Cantik-Itu-Luka-Cover-Baru-2017__w149_hauto.jpg",
                category: "Sastra",
                description: "Kisah magis realistis tentang Dewi Ayu dan keturunannya.",
                tags: ["Sastra", "Magis", "Sejarah"],
                discount: 9
            },
            {
                title: "Sebuah Seni untuk Bersikap Bodo Amat",
                author: "Mark Manson",
                publisher: "Gramedia Widiasarana Indonesia",
                publish_date: "2018-02-05",
                isbn: "978-602-03-8222-6",
                price: 85000,
                originalPrice: 95000,
                stock: 65,
                rating: 4.6,
                image: "https://cdn.gramedia.com/uploads/items/9786020382226_Sebuah-Seni-Untuk-Bersikap-Bodo-Amat__w149_hauto.jpg",
                category: "Pengembangan Diri",
                description: "Pendekatan yang waras demi menjalani hidup yang baik.",
                tags: ["Self Help", "Psikologi"],
                discount: 10
            },
            {
                title: "Pulang",
                author: "Tere Liye",
                publisher: "Republika Penerbit",
                publish_date: "2015-09-01",
                isbn: "978-602-0822-12-9",
                price: 89000,
                originalPrice: 99000,
                stock: 50,
                rating: 4.8,
                image: "https://cdn.gramedia.com/uploads/items/9786020822129_Pulang-Cover-Baru-2017__w149_hauto.jpg",
                category: "Aksi",
                description: "Novel aksi tentang perjalanan pulang seorang 'tukang pukul'.",
                tags: ["Aksi", "Petualangan", "Best Seller"],
                discount: 10
            },
            {
                title: "Perahu Kertas",
                author: "Dee Lestari",
                publisher: "Bentang Pustaka",
                publish_date: "2009-08-01",
                isbn: "978-602-291-129-6",
                price: 95000,
                originalPrice: 115000,
                stock: 40,
                rating: 4.7,
                image: "https://cdn.gramedia.com/uploads/items/9786022911296_Perahu-Kertas-Cover-Baru-2016__w149_hauto.jpg",
                category: "Romantis",
                description: "Kisah persahabatan dan cinta antara Kugy dan Keenan.",
                tags: ["Romance", "Remaja"],
                discount: 17
            },
            {
                title: "Negeri 5 Menara",
                author: "A. Fuadi",
                publisher: "Gramedia Pustaka Utama",
                publish_date: "2009-07-01",
                isbn: "978-979-22-4861-6",
                price: 85000,
                originalPrice: 100000,
                stock: 45,
                rating: 4.8,
                image: "https://cdn.gramedia.com/uploads/items/9789792248616_Negeri-5-Menara__w149_hauto.jpg",
                category: "Inspirasi",
                description: "Kisah persahabatan 6 santri di Gontor.",
                tags: ["Inspirasi", "Pendidikan", "Agama"],
                discount: 15
            },
            {
                title: "Hujan",
                author: "Tere Liye",
                publisher: "Gramedia Pustaka Utama",
                publish_date: "2016-01-01",
                isbn: "978-602-03-2478-3",
                price: 95000,
                originalPrice: 105000,
                stock: 50,
                rating: 4.8,
                image: "https://cdn.gramedia.com/uploads/items/9786020324783_Hujan-Cover-Baru-2016__w149_hauto.jpg",
                category: "Fiksi Ilmiah",
                description: "Novel tentang persahabatan, cinta, dan perpisahan di masa depan.",
                tags: ["Sci-Fi", "Romance", "Remaja"],
                discount: 9
            },
            {
                title: "Garis Waktu",
                author: "Fiersa Besari",
                publisher: "Media Kita",
                publish_date: "2016-09-01",
                isbn: "978-979-794-522-0",
                price: 78000,
                originalPrice: 88000,
                stock: 60,
                rating: 4.7,
                image: "https://cdn.gramedia.com/uploads/items/9789797945220_Garis-Waktu__w149_hauto.jpg",
                category: "Kumpulan Cerita",
                description: "Sebuah perjalanan menghapus luka.",
                tags: ["Puitis", "Romance", "Remaja"],
                discount: 11
            },
            {
                title: "Nanti Kita Cerita Tentang Hari Ini",
                author: "Marchella FP",
                publisher: "POP (Pustaka Obor Populer)",
                publish_date: "2018-10-01",
                isbn: "978-602-424-699-0",
                price: 125000,
                originalPrice: 145000,
                stock: 35,
                rating: 4.8,
                image: "https://cdn.gramedia.com/uploads/items/9786024246990_Nanti-Kita-Cerita-Tentang-Hari-Ini-Hard-Cover__w149_hauto.jpg",
                category: "Motivasi",
                description: "Buku visual grafis tentang pesan-pesan kehidupan.",
                tags: ["Visual", "Inspirasi", "Best Seller"],
                discount: 13
            }
        ];

        const books = await Book.bulkCreate(booksData);
        console.log('Books seeded!');

        // 3. Seed Purchases (Supply)
        const purchase = await Purchase.create({
            supplier_name: "Penerbit Utama",
            total_items: 200,
            total_cost: 15000000
        });

        // Add items to purchase
        await PurchaseItem.create({
            purchase_id: purchase.id,
            book_id: books[0].id,
            quantity: 50,
            cost_price: 50000
        });
        console.log('Purchases seeded!');

        // 4. Seed Vouchers
        await Voucher.bulkCreate([
            {
                code: 'WELCOME10',
                discount: 10,
                type: 'Percentage',
                minPurchase: 50000,
                maxDiscount: 20000,
                expiryDate: new Date(new Date().setMonth(new Date().getMonth() + 1)),
                status: 'Active'
            },
            {
                code: 'ONGKIRFREE',
                discount: 15000,
                type: 'Fixed',
                minPurchase: 100000,
                expiryDate: new Date(new Date().setMonth(new Date().getMonth() + 1)),
                status: 'Active'
            }
        ]);
        console.log('Vouchers seeded!');

        // 5. Seed Orders (For Dashboard & Order Management)
        // Order 1: John Doe - Paid
        const order1 = await Order.create({
            user_id: users[1].id,
            total_amount: books[0].price * 1 + books[1].price * 1,
            status: 'paid',
            invoice_number: 'INV/20260120/001',
            payment_method: 'QRIS',
            payment_proof: 'proof1.jpg',
            address: users[1].address
        });
        await OrderItem.create({ order_id: order1.id, book_id: books[0].id, quantity: 1, price: books[0].price });
        await OrderItem.create({ order_id: order1.id, book_id: books[1].id, quantity: 1, price: books[1].price });

        // Order 2: Jane Doe - Shipped
        const order2 = await Order.create({
            user_id: users[2].id,
            total_amount: books[5].price * 2,
            status: 'shipped',
            invoice_number: 'INV/20260121/002',
            payment_method: 'Transfer Bank',
            address: users[2].address
        });
        await OrderItem.create({ order_id: order2.id, book_id: books[5].id, quantity: 2, price: books[5].price });

        // Order 3: Budi - Pending
        const order3 = await Order.create({
            user_id: users[3].id,
            total_amount: books[2].price * 1,
            status: 'pending',
            invoice_number: 'INV/20260121/003',
            payment_method: 'QRIS',
            address: users[3].address
        });
        await OrderItem.create({ order_id: order3.id, book_id: books[2].id, quantity: 1, price: books[2].price });

        // Order 4: Admin (Testing) - Cancelled
        const order4 = await Order.create({
            user_id: users[0].id,
            total_amount: books[10].price * 1,
            status: 'cancelled',
            invoice_number: 'INV/20260119/004',
            payment_method: 'COD',
            address: users[0].address
        });
        await OrderItem.create({ order_id: order4.id, book_id: books[10].id, quantity: 1, price: books[10].price });

        console.log('Orders & OrderItems seeded!');

        // 6. Seed Reviews
        await Review.bulkCreate([
            {
                user_id: users[1].id,
                book_id: books[0].id,
                rating: 5,
                comment: "Buku yang sangat menginspirasi!"
            },
            {
                user_id: users[2].id,
                book_id: books[5].id,
                rating: 5,
                comment: "Sangat praktis dan mengubah hidup."
            },
            {
                user_id: users[3].id,
                book_id: books[0].id,
                rating: 4,
                comment: "Bagus, tapi kualitas kertas bisa ditingkatkan."
            }
        ]);
        console.log('Reviews seeded!');

        console.log('All data seeded successfully!');
        process.exit(0);
    } catch (error) {
        console.error('Failed to seed database:', error);
        process.exit(1);
    }
};

seedDatabase();
