from odoo import models, fields, api

class DineRecipe(models.Model):
    _name = 'dine360.recipe'
    _description = 'Restaurant Dish Recipe'

    product_tmpl_id = fields.Many2one(
        'product.template', 
        string='Dish', 
        required=True, 
        ondelete='cascade',
        domain=[('type', '=', 'consu')], # Usually dishes are consumables or service
        help="The finished dish that is sold to the customer."
    )
    
    ingredient_ids = fields.One2many(
        'dine360.recipe.line', 
        'recipe_id', 
        string='Ingredients'
    )

    total_cost = fields.Float(
        string='Total Ingredient Cost', 
        compute='_compute_total_cost', 
        store=True
    )

    @api.depends('ingredient_ids.subtotal_cost')
    def _compute_total_cost(self):
        for recipe in self:
            recipe.total_cost = sum(recipe.ingredient_ids.mapped('subtotal_cost'))

class DineRecipeLine(models.Model):
    _name = 'dine360.recipe.line'
    _description = 'Recipe Ingredient Line'

    recipe_id = fields.Many2one('dine360.recipe', string='Recipe', ondelete='cascade')
    product_id = fields.Many2one(
        'product.product', 
        string='Ingredient', 
        required=True,
        domain=[('type', '=', 'product')], # Ingredients must be storable products
        help="Raw materials like Rice, Chicken, Oil, etc."
    )
    quantity = fields.Float(string='Quantity', default=1.0, required=True)
    uom_id = fields.Many2one('uom.uom', string='Unit of Measure', related='product_id.uom_id', readonly=True)
    
    cost_price = fields.Float(string='Unit Cost', related='product_id.standard_price', readonly=True)
    subtotal_cost = fields.Float(string='Subtotal Cost', compute='_compute_subtotal_cost', store=True)

    @api.depends('quantity', 'product_id.standard_price')
    def _compute_subtotal_cost(self):
        for line in self:
            line.subtotal_cost = line.quantity * line.product_id.standard_price
