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

from odoo import models, fields, api
import time
from odoo.exceptions import UserError


class sos_inventory_customers(models.Model):
    _name = 'sos_inventory_customers'
    _description = 'Inventory Customers'
    _rec_name = 'customer_name'
    _order = 'id desc' 

    customer_name = fields.Char(string="Customer Name")
    customer_location = fields.Char(string="Location")
    @api.model
    def create(self, vals):
        new_name = (vals.get('customer_name') or '').lower()

        if new_name and len(new_name) >= 5:
            # Words/phrases to exclude
            blacklist = [
                'private limited', 'pvt ltd', 'pvt. ltd.', 'ltd', 'llp', 'inc', 'co', 'company', 'corporation'
            ]

            def clean_name(name):
                for word in blacklist:
                    name = name.replace(word, '')
                return name.strip()

            new_name_clean = clean_name(new_name)

            existing_customers = self.search([])
            for customer in existing_customers:
                existing_name = (customer.customer_name or '').lower()
                existing_name_clean = clean_name(existing_name)

                # Check all substrings of length 7 or more
                for i in range(len(new_name_clean) - 6):
                    substring = new_name_clean[i:i+7]
                    if substring in existing_name_clean:
                        raise UserError(
                            f"A customer with a similar name already exists: '{customer.customer_name}' "
                            f"(matched substring: '{substring}')"
                        )

        return super().create(vals)