# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import ValidationError


class SOS_Serial_Batch_Tracker(models.Model):
    _name = 'sos_serial_batch_tracker'
    _description = 'Batch Number & Serial No Tracker'

    name = fields.Char(string="Ref ID",default=lambda self: self._generate_id(),readonly= True, required= True)
    customer_name = fields.Selection(selection="_get_unique_customers", string="Customer Name", required=True)
    batch_no = fields.Char(string='Batch No')
    serial_no = fields.Text(string='Serial No')
    indent_no  = fields.Many2one('sos_fg_plan', string='Indent Ref No')
    serial_ids = fields.One2many("sos_serial_batch_tracker_line", "record_id", string="Serial Numbers")  # Stored properly
    @api.model
    def _get_unique_customers(self):
        """Fetch unique customer names from sos_sales_order"""
        customer_records = self.env['sos_sales_order'].search([]).mapped("customer_name")
        unique_customers = sorted(set(filter(None, customer_records)))  # Remove duplicates & empty values
        return [(customer, customer) for customer in unique_customers]  # Format for Selection field
    @api.onchange("serial_no")
    def action_serial_no(self):
        """Convert pasted serials into One2many entries"""
        if self.serial_no:
            serial_numbers = list(filter(None, map(str.strip, self.serial_no.split("\n"))))  # Split by newline
            existing_serials = self.serial_ids.mapped("serial_number")

            # Remove duplicates before adding
            new_serials = [num for num in serial_numbers if num not in existing_serials]

            self.serial_ids = [(0, 0, {"serial_number": num}) for num in new_serials]

    def _generate_id(self):
        sequence_util = self.env['sos_common_scripts']
        return sequence_util.generate_sequence('sos_serial_batch_tracker','B&S', 'name')

class SOS_Serial_Batch_Tracker_Line(models.Model):
    _name = "sos_serial_batch_tracker_line"

    record_id = fields.Many2one("sos_serial_batch_tracker", string="Parent Record", ondelete="cascade")
    serial_number = fields.Char(string="Serial Number", required=True, index=True)