from odoo import models, fields, tools

class HazardInventoryReport(models.Model):
    _name = "hazard.inventory.report"
    _description = "Reporte de Inventario con Precio y Costo"
    _auto = False

    location_id = fields.Many2one('stock.location', string='Ubicación', readonly=True)
    product_id = fields.Many2one('product.product', string='Producto', readonly=True)
    product_tmpl_id = fields.Many2one('product.template', string='Plantilla de Producto', readonly=True)
    categ_id = fields.Many2one('product.category', string='Categoría', readonly=True)
    quantity = fields.Float(string='Cantidad', readonly=True)
    standard_price = fields.Float(string='Costo Unitario', readonly=True)
    list_price = fields.Float(string='Precio Venta Unitario', readonly=True)
    total_cost = fields.Float(string='Costo Total', readonly=True)
    total_sale = fields.Float(string='Valor Venta Total', readonly=True)

    def _query(self):
        return """
            SELECT 
                sq.id AS id,
                sq.location_id,
                sq.product_id,
                pp.product_tmpl_id,
                pt.categ_id,
                sq.quantity,
                COALESCE(
                    (SELECT value_float 
                     FROM ir_property 
                     WHERE name = 'standard_price' 
                       AND (res_id = 'product.product,' || pp.id OR res_id = 'product.template,' || pt.id) 
                     ORDER BY res_id DESC, id DESC LIMIT 1),
                    0
                ) AS standard_price,
                COALESCE(pt.list_price, 0) AS list_price,
                (sq.quantity * COALESCE(
                    (SELECT value_float 
                     FROM ir_property 
                     WHERE name = 'standard_price' 
                       AND (res_id = 'product.product,' || pp.id OR res_id = 'product.template,' || pt.id) 
                     ORDER BY res_id DESC, id DESC LIMIT 1),
                    0
                )) AS total_cost,
                (sq.quantity * COALESCE(pt.list_price, 0)) AS total_sale
            FROM stock_quant sq
            JOIN stock_location sl ON sq.location_id = sl.id
            JOIN product_product pp ON sq.product_id = pp.id
            JOIN product_template pt ON pp.product_tmpl_id = pt.id
            WHERE sl.usage = 'internal'
              AND sq.quantity != 0
        """

    def init(self):
        tools.drop_view_if_exists(self.env.cr, self._table)
        self.env.cr.execute("""CREATE or REPLACE VIEW %s as (%s)""" % (self._table, self._query()))
