import { prisma } from "../src/core/prisma"
import { hash } from "bcrypt"
import {ShopUserRole} from "@prisma/client"

async function main() {
    console.log("🌱 Seeding...")

    const hashedAdminPassword = await hash("test1234", 10)
    const hashedPosPassword = await hash("pos1234", 10)

    // ── Admin user ────────────────────────────────────────
    const admin = await prisma.user.upsert({
        where: { email: "jeremy.lesouhaitier@gmail.com" },
        update: {},
        create: {
            email: "jeremy.lesouhaitier@gmail.com",
            password: hashedAdminPassword
        }
    })

    console.log("✅ Admin user created:", admin.email)

    // ── Shop ──────────────────────────────────────────────
    const existingShop = await prisma.shop.findFirst({
        where: { ownerId: admin.id }
    })

    const shop = existingShop ?? await prisma.shop.create({
        data: {
            name: "Ma Boutique",
            ownerId: admin.id
        }
    })

    console.log("✅ Shop created:", shop.name)

    // ── Stations ──────────────────────────────────────────
    const caisse = await prisma.station.upsert({
        where: { id: "seed-station-caisse" },
        update: {},
        create: { id: "seed-station-caisse", shopId: shop.id, name: "Caisse 1", mainType: "CASH" }
    })
    const cuisine = await prisma.station.upsert({
        where: { id: "seed-station-cuisine" },
        update: {},
        create: { id: "seed-station-cuisine", shopId: shop.id, name: "Cuisine", mainType: "PRODUCTION" }
    })
    console.log("✅ Stations créées:", caisse.name, cuisine.name)

    // ── Route logistique : Cuisine → livraison Caisse ────
    const existingRoute = await prisma.logisticsRoute.findFirst({ where: { shopId: shop.id, name: "Route Standard" } })
    const route = existingRoute ?? await prisma.logisticsRoute.create({
        data: {
            shopId: shop.id,
            name: "Route Standard",
            isDefault: true,
            steps: {
                create: [
                    { position: 0, stepType: "PRODUCTION", stationId: cuisine.id },
                    { position: 1, stepType: "TRANSPORT", destinationStationId: caisse.id, handlerMode: "RUNNER" },
                ]
            }
        }
    })
    // Aussi mettre comme route par défaut du shop
    await prisma.shop.update({ where: { id: shop.id }, data: { defaultLogisticsRouteId: route.id } })
    console.log("✅ Route logistique créée:", route.name)

    // ── Catégorie + Produits ──────────────────────────────
    const existingCat = await prisma.category.findFirst({ where: { shopId: shop.id, name: "Snacks" } })
    const cat = existingCat ?? await prisma.category.create({
        data: { shopId: shop.id, name: "Snacks" }
    })

    const existingTartine = await prisma.product.findFirst({ where: { shopId: shop.id, name: "Tartine" } })
    if (!existingTartine) {
        await prisma.product.create({
            data: { shopId: shop.id, name: "Tartine", price: 350, vatRate: 10, categoryId: cat.id, logisticsRouteId: route.id }
        })
    }
    const existingCoca = await prisma.product.findFirst({ where: { shopId: shop.id, name: "Coca" } })
    if (!existingCoca) {
        await prisma.product.create({
            data: { shopId: shop.id, name: "Coca", price: 200, vatRate: 20, categoryId: cat.id }
        })
    }
    console.log("✅ Produits créés (Tartine avec route, Coca sans)")

    // ── ShopUser (vendeur POS) ─────────────────────────────
    await createShopUser(shop.id, "laurane.barraux@gmail.com", "CASHIER")
    await createShopUser(shop.id, "chloe.castellon@gmail.com", "CASHIER")
    await createShopUser(shop.id, "jeremy.lesouhaitier@gmail.com", "MANAGER")
    await createShopUser(shop.id, "ilan.lesouhaitier@gmail.com", "RUNNER")

    console.log("✅ Seed terminé")
}

async function createShopUser(shopId: string, email: string, role: ShopUserRole) {
    const existingShopUser = await prisma.shopUser.findFirst({
        where: { shopId, email }
    })

    if (existingShopUser) {
        console.log("ℹ️  ShopUser already exists: ", existingShopUser.email)
        return existingShopUser
    }

    const hashedPosPassword = await hash("pos1234", 10);
    const displayName = (email.split("@")[0].split(".")[0]).charAt(0).toUpperCase() + email.split("@")[0].split(".")[0].slice(1);
    await prisma.shopUser.create({
        data: {
            shopId,
            email,
            displayName,
            username: email,
            password: hashedPosPassword,
            role,
            mustChangePassword: false
        }
    })

    console.log("ℹ️  ShopUser created : ", email)
}

main()
    .finally(async () => {
        await prisma.$disconnect()
    })