-- Customer product favorites (per business)

CREATE TABLE favorites (
  id          BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
  business_id BIGINT NOT NULL,
  user_id     BIGINT NOT NULL,
  product_id  BIGINT NOT NULL,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),

  CONSTRAINT favorites_business_id_fkey
    FOREIGN KEY (business_id) REFERENCES businesses (id) ON DELETE CASCADE,
  CONSTRAINT favorites_user_id_fkey
    FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
  CONSTRAINT favorites_product_id_fkey
    FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE,
  CONSTRAINT favorites_business_user_product_unique
    UNIQUE (business_id, user_id, product_id)
);

CREATE INDEX idx_favorites_business_user_created
  ON favorites (business_id, user_id, created_at DESC);

CREATE INDEX idx_favorites_product_id
  ON favorites (product_id);

CREATE TRIGGER favorites_set_updated_at
  BEFORE UPDATE ON favorites
  FOR EACH ROW
  EXECUTE FUNCTION set_updated_at();

INSERT INTO permissions (name, slug, group_name, description) VALUES
  ('Add own favorites',    'favorites.create', 'favorites', 'Add products to own favorites'),
  ('Remove own favorites', 'favorites.delete', 'favorites', 'Remove products from own favorites')
ON CONFLICT (slug) DO NOTHING;

INSERT INTO role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM roles r
JOIN permissions p ON p.slug IN ('favorites.create', 'favorites.delete')
WHERE r.slug = 'customer'
ON CONFLICT DO NOTHING;
