package com.example.barokahstore.data

import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader

data class ParsedProduct(
    val barcode: String,
    val name: String,
    val buyPrice: Double,
    val sellPrice: Double,
    val stock: Int,
    val unit: String,
    val categoryName: String?
)

object CsvHelper {
    
    fun generateCsvTemplate(): String {
        val builder = StringBuilder()
        builder.append("barcode,name,buyPrice,sellPrice,stock,unit,categoryName\n")
        builder.append("8992741901115,Indomie Goreng Spesial,2600,3100,120,Bks,Makanan\n")
        builder.append("8991389221151,Aqua Gelas 220ml,500,1000,240,Pcs,Minuman\n")
        builder.append("8999999039912,Pepsodent Pencegah Gigi Berlubang 190g,12500,15000,15,Pcs,Kebutuhan Rumah\n")
        return builder.toString()
    }

    fun parseCsv(inputStream: InputStream): List<ParsedProduct> {
        val list = mutableListOf<ParsedProduct>()
        val reader = BufferedReader(InputStreamReader(inputStream))
        try {
            var line: String? = reader.readLine() // Read header
            if (line == null) return list
            
            // Loop data lines
            while (reader.readLine().also { line = it } != null) {
                val row = line ?: continue
                if (row.trim().isEmpty()) continue
                
                // Split by comma (handles standard comma separation)
                val tokens = row.split(",")
                if (tokens.size >= 6) {
                    val barcode = tokens[0].trim()
                    val name = tokens[1].trim()
                    val buyPrice = tokens[2].trim().toDoubleOrNull() ?: 0.0
                    val sellPrice = tokens[3].trim().toDoubleOrNull() ?: 0.0
                    val stock = tokens[4].trim().toIntOrNull() ?: 0
                    val unit = tokens[5].trim()
                    val categoryName = if (tokens.size > 6) tokens[6].trim().ifEmpty { null } else null
                    
                    if (barcode.isNotEmpty() && name.isNotEmpty()) {
                        list.add(
                            ParsedProduct(
                                barcode = barcode,
                                name = name,
                                buyPrice = buyPrice,
                                sellPrice = sellPrice,
                                stock = stock,
                                unit = unit,
                                categoryName = categoryName
                            )
                        )
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            try {
                reader.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return list
    }
}
